Skip to content
UoL CS Notes

Lecture 26-2

COMP105 Lectures

Lazy Lists

Lists are never evaluated until they are needed. This means that take 1 [1..10] is just as efficient as take 1 [1..1000].

Infinite Lists

The reason why we are able to make infinite lists is a result of lazy evaluation. As evaluation only happens right at the end, the program won’t hang by trying to evaluate it in the background. You can make simple infinite list like so:

[1,1..]

Or like this:

all1s :: [Int]
all1s = 1 : all1s

As a result of this you are able to do infinite computations on infinite lists provided that you can resolve to a finite value.

all2s = zipwith (+) all1s all1s

This will produce an infinite sum of infinite lists.

Example

sieve (x:xs) = x : filter (\y -> y `mod` x /= 0) (sieve xs)

You can then use this function to define other useful infinite lists:

primes = sieve [2..]
> take 10 primes
[2,3,]
> primes !! 1000
7927

The $ Operator

The $ function evaluates a function.

Take this function and apply it to this argument

Strict Evaluation

The $! operator makes Haskell evaluate strictly:

> let f x = 1

> f $ undefined
1

> f $! undefined
Error

For most code you won’t notice the difference but it can change the error outputs.