Programming with lazy evaluation
The key benefit of lazy evaluation is that it allows for a much more compositional style of programming. Instead of writing large blocks of code from scratch, we can frequently assemble functionality out of highly reusable functions. Many key use cases of that revolve around lists.
Streaming
Let us consider what happens in the following scenario:
*Main> [1..5]
Behind the scenes, GHCi
calls show
on [1..5]
to display the resulting list. As a reminder, we show the definitions of the key functions involved. First, the enumeration [1..5]
is generated by the enumFromTo
method of the Enum
class:
Prelude
enumFromTo :: Integer -> Integer -> Integer
enumFromTo l h
| l <= h = l : enumFromTo (l+1) h
| otherwise = []
Secondly, show l
is defined as showList
l ""
:
Prelude
showList :: [Integer] -> String -> String
showList [] s = "[]" ++ s
showList (x:xs)...