Personal tools

Lazy evaluation

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
(cyclic graphs of pointers)

Revision as of 08:47, 29 November 2007

Lazy evaluation means Non-strict semantics and Sharing. A kind of opposite is eager evaluation.

Non-strict semantics allows to bypass undefined values (e.g. results of infinite loops) and this way it also allows to process formally infinite data.

When it comes to machine level and efficiency issues then it is important whether equal objects share the same memory.

A Haskell program cannot observe whether
2+2 :: Int
4 :: Int
are different objects in the memory.

In many cases it is also not necessary to know it, but in some cases the difference between shared and separated objects yields different orders of space or time complexity.

Consider the infinite list
 let x = 1:x in x
. For the non-strict semantics it would be ok to store this as a flat list
 1 : 1 : 1 : 1 : ...
, with memory consumption as big as the number of consumed

But with lazy evaluation (i.e. sharing) this becomes a list with a loop, a pointer back to the beginning. It does only consume constant space. In an imperative language (here Modula-3) the same would be achieved with the following code:

  List =
          next:  List;
          value: INTEGER;
  x := NEW(List, value:=1);
BEGIN := x;

That is lazy evaluation allows us to define cyclic graphs of pointers with warrantedly valid pointers. In contrast to that C allows cyclic graphs of pointers, but pointers can be uninitialized, which is a nasty security hole. Java forces pointers to be initialized but since it evaluates eagerly, the graphs of pointers always remain acyclic.

See also