How can I make a lazy list representing a sequence of doubling numbers? Example:
1 2 4 8 16 32
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.
Functional languages like Haskell are lazy evaluated, but not OCaml, which is eagerly evaluated.
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.
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)))
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With