This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

[Caml-list] yet another question on lazy lists
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2002-07-06 (14:18) From: Michael Vanier Subject: [Caml-list] yet another question on lazy lists
```
First off, thanks very much to all of you who have helped me understand
lazy evaluation in ocaml.  Now for another question: I get a strange type
error from the following code:

(* "stream" means lazy lists for my purposes. *)
type 'a stream =
Nil
| Cons of 'a * 'a stream Lazy.t

let stream_cons x y = Cons (x, lazy y)

let stream_hd s =
match s with
Nil -> invalid_arg "stream_hd"
| Cons (x, y) -> x

let stream_tl s =
match s with
Nil -> invalid_arg "stream_tl"
| Cons (x, y) -> Lazy.force y

let rec stream_map2 proc s1 s2 =
match (s1, s2) with
(Cons (x1, y1), Cons (x2, y2)) ->
Cons ((proc x1 x2), lazy (stream_map2 proc
(Lazy.force y1)
(Lazy.force y2)))
| _ -> invalid_arg "stream_map2"

stream_map2 (+) s1 s2

(* Generating fibonacci numbers. *)

let rec fibs =
Cons (0,
lazy (Cons (1,
(stream_tl fibs)
fibs))))

Thus far, everything works properly.  But when I try to convert the "Cons"
expressions into "stream_cons" function calls, I get a weird type error:

let rec fibs2 =
stream_cons 0 (stream_cons 1 (add_streams (stream_tl fibs2) fibs2))

# let rec fibs2 =
stream_cons 0 (stream_cons 1 (add_streams (stream_tl fibs2) fibs2))
-------------------------------------------------------------------
;;
This kind of expression is not allowed as right-hand side of `let rec'

What does this mean?  My best guess is that ocaml sees that you're defining
a value in terms of itself (like e.g. "let rec a = 2 * a") and won't allow
it, but that doesn't explain why the lazy version works.  Does this mean
that my "stream_cons" function is useless?