Both achieve the same thing
# let x = fun () -> begin print_endline "Hello"; 1 end;;
val x : unit -> int = <fun>
# x ();;
Hello
- : int = 1
# let y = lazy begin print_endline "World"; 2 end;;
val y : int lazy_t = <lazy>
# Lazy.force y;;
World
- : int = 2
Is there any reason one should be preferred over the other? Which one is more efficient?
Functional languages like Haskell are lazy evaluated, but not OCaml, which is eagerly evaluated.
The special expression syntax lazy (expr) makes a suspension of the computation of expr , without computing expr itself yet. " Forcing" the suspension will then compute expr and return its result.
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.
Lazy evaluation is a programming strategy that allows a symbol to be evaluated only when needed. In other words, a symbol can be defined (e.g in a function), and it will only be evaluated when it is needed (and that moment can be never). This is why you can do: plop <- function(a, b){ a * 10.
First of all, they do not behave the same, try to do Lazy.force y
yet another time, and you will notice the difference, the "World"
message is no longer printed, so the computation is not repeated, as the result was remembered in the lazy value.
This is the main difference between lazy computations and thunks. They both defer the computation until the time when they are forced. But the thunk will evaluate its body every time, where the lazy value will be evaluated once, and the result of the computation will be memoized.
Underneath the hood, the lazy value is implemented as a thunk object with a special flag. When runtime first calls the lazy value, it substitutes the body of the thunk with the result of computation. So, after the first call to Lazy.force y
, the y
object actually became an integer 2
. So the consequent calls to Lazy.force
do nothing.
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