Haskell only evaluates an expression if it is needed for the computation as a whole:
xis never used, so is never evaluated, and the error never gets triggered.
xis never used here either, because if the first argument of
True, it returns
Truewithout evaluating the second.
- undefined is a value that will throw a runtime error when evaluated.
A common use case of lazy evaluation is to define an infinite piece of data, and only take a finite part.
[1..]is an infinite list of all the integers (
Infinite lists in Haskell are similar to generators in Python, which can be thought of as the special case of lazy evaluation for lists.
However, laziness applies to data structures other than lists, and is a pervasive feature of the language.
As a consequence, it is common to build an infinite structure recursively, and only consume a part, such as a finite prefix of this infinite list of prime numbers:
The consequences of laziness for algorithmic complexity analysis of purity and laziness are wide-ranging. For a good overview, see this article
take 10 func1 gives
A deeper dive¶
See here for more resources on lazy algorithms and the performance implications of laziness.