How to imitate laziness

I watched an interview with John Hughes, and they asked him if he had missed laziness when he switched from Haskell to Erlang. In response, he said yes, and he used imitation tools. My question is: how to emulate laziness in a strict language? It would be nice to see examples used in common languages.

+7
source share
3 answers

The usual trick is to use lambda (I think that would be fun in Erlang).

Here is an example using Ruby:

Monad equivalent in Ruby

The basic idea is quite simple ... You take any expression that you want to make lazy, wrap it with an anonymous function with a null argument, and then evaluate this function when you want it forcibly.

+7
source

If you only want to emulate non-strictness, then you only need to wrap the expression in a function and call it if necessary.

If you really want to imitate laziness (i.e. not rigor with memoization), then you need to wrap this function in a mutable link. Sketch in OCaml (ignoring exceptions):

 type 'a lazy = 'a thunk ref and 'a thunk = Lazy of unit -> 'a | Memo of 'a let lazy f = ref (Lazy f) let force l = match !l with | Lazy f -> let x = f () in l := Memo x; x | Memo x -> x 

Except that OCaml already has this predefined in its library (in a way that also handles exceptions from f).

+2
source

You might want to look at the python generators in detail.

In short, these are objects that have a __next__ message that allows them to retrieve a single element. Thus, they can be composed so that the processing at each step pulls the element from the next generated generator.

Thus, python programmers can easily work with infinite sequences (or sequences of length one).

+1
source

All Articles