Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml: Lazy Lists

How can I make a lazy list representing a sequence of doubling numbers? Example:

1 2 4 8 16 32
like image 460
Nick Heiner Avatar asked Oct 27 '09 16:10

Nick Heiner


People also ask

Is OCaml lazy?

By default, Ocaml is an eager language, but you can use the “lazy” features to build lazy datatypes. Other funcional languages, notably Haskell, are lazy by default.

Does OCaml use lazy evaluation?

Functional languages like Haskell are lazy evaluated, but not OCaml, which is eagerly evaluated.

What is lazy force?

Forces of static friction and normal forces are similar in that they tend to prevent the surfaces of objects from moving with respect to one another. For example, normal force interaction might prevent a book from falling through a table.


2 Answers

Using streams:

let f x = Stream.from (fun n -> Some (x * int_of_float (2.0 ** float_of_int n)))

or

let f x =
  let next = ref x in
    Stream.from (fun _ -> let y = !next in next := 2 * y ; Some y)

Using a custom lazy_list type:

type 'a lazy_list =
  | Nil
  | Cons of 'a * 'a lazy_list lazy_t
let rec f x = lazy (Cons (x, f (2*x)))
like image 58
ephemient Avatar answered Sep 20 '22 15:09

ephemient


The great blog enfranchised mind has a great article on this topic:

http://enfranchisedmind.com/blog/posts/ocaml-lazy-lists-an-introduction/

You can also check out http://batteries.forge.ocamlcore.org/doc.preview%3Abatteries-beta1/html/api/Lazy%5Flist.html

which is the standard library for dealing with this.

This question is also very similar to this question:

What OCaml libraries are there for lazy list handling?

like image 21
chollida Avatar answered Sep 22 '22 15:09

chollida