Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml lazy evaluation: 'a lazy_t vs unit -> 'a

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?

like image 402
Chris Avatar asked Nov 16 '16 17:11

Chris


People also ask

Does OCaml use lazy evaluation?

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

What is lazy in OCaml?

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.

Is OCaml lazy or eager?

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.

What is lazy evaluation in R?

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.


1 Answers

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.

like image 101
ivg Avatar answered Nov 06 '22 17:11

ivg