I got a Stack_overflow error when take n elements from a stream

(* here is my stream *)
type 'a stream 
  = Nil 
  | Cons of 'a * (unit -> 'a stream)

(* the take function *)
let rec take n s =
  if n <= 0
  then [] 
  else
    match s with
      | Nil -> []
      | Cons (n, g) -> n :: (take (n - 1) (g ()))

(* the from function *)
let rec from n = Cons (n, fun () -> from (n + 1))

(* Fatal error: exception Stack_overflow !! *)
let ten = take 10 (from 2)

edit
When I run code on TryOCaml (ocamlpro.com), it show the error message:

Stack overflow during evaluation (looping recursion?).

look at the cons line.

I got it… what a stupid bug :joy:

So, I didn’t actually carefully read your code. Instead, I loaded into a toplevel and used #trace take ;; and it was obvious. #trace is your friend.

let rec take n s =
  if n <= 0
  then [] 
  else
    match s with
      | Nil -> []
      | Cons (cur, g) -> cur :: (take (n - 1) (g ()))