i’m new to ocaml and i’m trying to create a function that takes an int list and turn it into a list of int list that are have the first element + the second element, followed by the rest of the list, until there is one element left, for example:
[1; 2; 0; 4; 2; 1]
[3; 0; 4; 2; 1]
[3; 4; 2; 1]
[7; 2; 1]
[9; 1]
[10]
And here is my code:
let rec nth l k =
match l with
| [] -> 0
| s::t -> if k = 0 then s else nth t (k - 1);;
let no_first l =
match l with
| [] -> []
| s::t -> t
let rec left_comp_once l =
match l with
| [] -> []
| s::t -> (s + nth t 0) :: no_first t
let rec left_comps l =
match l with
| [] -> []
| s::t -> let x = (s + nth t 0) :: no_first t in
[x] @ left_comps x
The left_comp_once function works, however, i get looping recursion error when i try the left_comps function
I cannot figure out where the issue is coming from
Also, i would like to have a return element in this format:
int list -> (int list) list
However, what i wrote gives me:
int list -> int list list
What do these parenthesis imply ?
>Solution :
If you look at this expression:
let x = (s + nth t 0) :: no_first t in
[x] @ left_comps x
you can see that x can’t possibly be an empty list. It always has at least one element. Therefore left_comps will never terminate when given a non-empty list.