Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Stack overflow during evaluation (looping recursion?)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading