OCaml lazy rating: 'a lazy_t vs unit ->' a
Both achieve the same *
# 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 why one should be preferable to another? Which one is more effective?
First of all, they do not behave the same way, try again Lazy.force y, and you will notice the difference, the message is "World"no longer printed, therefore, the calculation is not repeated, since the result was stored in a lazy value.
thunks. , . thunk , lazy , .
- . , thunk . , Lazy.force y y 2. Lazy.force .