PROGRAMMING IN HASKELL
description
Transcript of PROGRAMMING IN HASKELL
1
PROGRAMMING IN HASKELL
Chapter 12 – Lazy evaluation and infinite lists
Slides not from Hutton
Redex
2
A reducible expression (redex) is a function that can be applied to its arguments.
The expression (1+2)*(3+4) is not reducible since both arguments must be evaluated before it can be applied.
The redexs are (1+2) and (3+4) but not (1+2)*(3+4).
But once (1+2) and (3+4) have been reduced to 3 and 7 respectively, 3*7 is a redex.
Outermost first
Consider int :: Intinf = 1 + inf
But
Run it and get a stack overflow.
> inf where inf = 1+infERROR - C stack overflow
> fst (0, inf) where inf = 1 + inf0> snd (inf, 0) where inf = 1 + inf0
fst (0, _) and snd (_, 0) are both reducible. No need to reduce the other tuple element.
3
4
Outermost first
ones :: [Int]ones = 1 : ones
Consider
Run it and get an infinite list. (Use Actions -> stop to stop it.)
> take 5 ones where ones = 1:ones[1,1,1,1,1]
ones = [1, 1, …]
5
> take 5 ones= take 5 1: ones= take 5 1:1:ones= take 5 1:1:1:ones= take 5 1:1:1:1:ones= take 5
1:1:1:1:1:ones= [1, 1, 1, 1, 1]
At this point take 5 xs can be evaluated. So it is.
Inner expressions are evaluated only until outer expressions can be.
primes :: [Int]primes = seive [2 .. ]
sieve :: [Int] [Int]sieve (p:xs) = p : sieve [x | x xs, x `mod` p
0]
6
Note: [1 .. ] = [1, 2, 3, 4, … ]
> take 5 [1 ..][1,2,3,4,5]
Sieve of Eratosthenes. Generate the primes one by one, eliminating all multiples of generated primes.
> take 5 primes where primes = sieve [2 .. ]; sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p /= 0][2,3,5,7,11]
Primes
> take 4 primes= take 4 sieve [2 .. ] = take 4 sieve (2:[3 .. ])= take 4 (2 : sieve [x | x [3 .. ], x `mod` 2 0])= take 4 (2 : sieve (3:[x | x [4 .. ], x `mod` 2 0]))= take 4 (2 : 3 : sieve [y | y [x | x [4 .. ], x `mod` 2 0], y `mod` 3 0]= take 4 (2 : 3 : sieve [y | y [x | x [5 .. ], x `mod` 2 0], y `mod` 3 0] = take 4 (2 : 3 : sieve [y | y 5:[x | x [6 .. ], x `mod` 2 0], y `mod` 3 0] = take 4 (2 : 3 : sieve (5:[y | y [x | x [6 .. ], x `mod` 2 0], y `mod` 3
0])) = take 4 (2 : 3 : 5 : sieve [z | z [y | y [x | x [6 .. ], x `mod` 2 0], y `mod`
3 0], z `mod` 5 0]) = take 4 (2 : 3 : 5 : sieve [z | z [y | y [x | x [7 .. ], x `mod` 2 0], y `mod`
3 0], z `mod` 5 0]) = take 4 (2 : 3 : 5 : sieve [z | z [y | y (7:[x | x [8 .. ], x `mod` 2 0]), y
`mod` 3 0], z `mod` 5 0]) = take 4 (2 : 3 : 5 : sieve [z | z 7:[y | y [x | x [8 .. ], x `mod` 2 0], y
`mod` 3 0], z `mod` 5 0]) = take 4 (2 : 3 : 5 : sieve (7:[z | z [y | y [x | x [8 .. ], x `mod` 2 0], y
`mod` 3 0], z `mod` 5 0]))= take 4 (2 : 3 : 5 : 7 : sieve [w | w [z | z [y | y [x | x [8 .. ], x `mod` 2
0], y `mod` 3 0], z `mod` 5 0], w `mod` 7 0] ) = [2, 3, 5, 7]
The color coding lets you follow each list. [2 .. ] = 2 : [3 .. ]
sieve (p:xs) = p : sieve [x | x xs, x `mod` p 0]
7
Primes
Fibonacci numbers
Exercise 4.> take 9 fibs where fibs = 0 : 1 : [x + y | (x, y) <- zip fibs (tail fibs)][0,1,1,2,3,5,8,13,21]
8