-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChapter17.hs
More file actions
420 lines (255 loc) · 8.16 KB
/
Copy pathChapter17.hs
File metadata and controls
420 lines (255 loc) · 8.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
-- Haskell: The Craft of Functional Programming
-- Simon Thompson
-- (c) Addison-Wesley, 1999.
-- Chapter 17
-- Lazy programming
-- ^^^^^^^^^^^^^^^^
module Chapter17 where
import List hiding (union) -- for \\
import Chapter19 hiding (map,fac) -- for iSort
import Set -- for Relation
import Relation -- for graphs
-- Lazy evaluation
-- ^^^^^^^^^^^^^^^
-- Some example functions illustrating aspects of laziness.
f x y = x+y
g x y = x+12
switch :: Int -> a -> a -> a
switch n x y
| n>0 = x
| otherwise = y
h x y = x+x
pm (x,y) = x+1
-- Calculation rules and lazy evaluation
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- Some more examples.
f1 :: [Int] -> [Int] -> Int
f1 [] ys = 0
f1 (x:xs) [] = 0
f1 (x:xs) (y:ys) = x+y
f2 :: Int -> Int -> Int -> Int
f2 m n p
| m>=n && m>=p = m
| n>=m && n>=p = n
| otherwise = p
f3 :: Int -> Int -> Int
f3 a b
| notNil xs = front xs
| otherwise = b
where
xs = [a .. b]
front (x:y:zs) = x+y
front [x] = x
notNil [] = False
notNil (_:_) = True
-- List comprehensions revisited
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- Simpler examples
-- ^^^^^^^^^^^^^^^^
-- All pairs formed from elements of two lists
pairs :: [a] -> [b] -> [(a,b)]
pairs xs ys = [ (x,y) | x<-xs , y<-ys ]
pairEg = pairs [1,2,3] [4,5]
-- Illustrating the order in which elements are chosen in multiple
-- generators.
triangle :: Int -> [(Int,Int)]
triangle n = [ (x,y) | x <- [1 .. n] , y <- [1 .. x] ]
-- Pythagorean triples
pyTriple n
= [ (x,y,z) | x <- [2 .. n] , y <- [x+1 .. n] ,
z <- [y+1 .. n] , x*x + y*y == z*z ]
-- Calculating with list comprehensions
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- The running example from this section.
runningExample = [ x+y | x <- [1,2] , isEven x , y <- [x .. 2*x] ]
isEven :: Int -> Bool
isEven n = (n `mod` 2 == 0)
-- List permutations
-- ^^^^^^^^^^^^^^^^^
-- One definition of the list of all permutations.
perms :: Eq a => [a] -> [[a]]
perms [] = [[]]
perms xs = [ x:ps | x <- xs , ps <- perms (xs\\[x]) ]
-- Another algorithm for permutations
perm :: [a] -> [[a]]
perm [] = [[]]
perm (x:xs) = [ ps++[x]++qs | rs <- perm xs ,
(ps,qs) <- splits rs ]
-- All the splits of a list into two halves.
splits :: [a]->[([a],[a])]
splits [] = [ ([],[]) ]
splits (y:ys) = ([],y:ys) : [ (y:ps,qs) | (ps,qs) <- splits ys]
-- Vectors and Matrices
-- ^^^^^^^^^^^^^^^^^^^^
-- A vector is a sequence of real numbers,
type Vector = [Float]
-- and the scalar product of two vectors.
scalarProduct :: Vector -> Vector -> Float
scalarProduct xs ys = sum [ x*y | (x,y) <- zip xs ys ]
-- The type of matrices.
type Matrix = [Vector]
-- and matrix product.
matrixProduct :: Matrix -> Matrix -> Matrix
matrixProduct m p
= [ [scalarProduct r c | c <- columns p] | r <- m ]
-- where the function columns gives the representation of a matrix as a
-- list of columns.
columns :: Matrix -> Matrix
columns y = [ [ z!!j | z <- y ] | j <- [0 .. s] ]
where
s = length (head y)-1
-- Refutable patterns: an example
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
refPattEx = [ x | (x:xs) <- [[],[2],[],[4,5]] ]
-- Data-directed programming
-- ^^^^^^^^^^^^^^^^^^^^^^^^^
-- Summing fourth powers of numbers up to n.
sumFourthPowers :: Int -> Int
sumFourthPowers n = sum (map (^4) [1 .. n])
-- List minimum: take the head of the sorted list. Only makes sense in an
-- lazy context.
minList :: [Int] -> Int
minList = head . iSort
-- Example: routes through a graph
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- A example graph.
graphEx = makeSet [(1,2),(1,3),(2,4),(3,5),(5,6),(3,6)]
-- Look for all paths from one point to another. (Assumes the graph is acyclic.)
routes :: Ord a => Relation a -> a -> a -> [[a]]
routes rel x y
| x==y = [[x]]
| otherwise = [ x:r | z <- nbhrs rel x ,
r <- routes rel z y ]
--
-- The neighbours of a point in a graph.
nbhrs :: Ord a => Relation a -> a -> [a]
nbhrs rel x = flatten (image rel x)
-- Example evaluations
routeEx1 = routes graphEx 1 4
routeEx2 = routes graphEx 1 6
-- Accommodating cyclic graphs.
routesC :: Ord a => Relation a -> a -> a -> [a] -> [[a]]
routesC rel x y avoid
| x==y = [[x]]
| otherwise = [ x:r | z <- nbhrs rel x \\ avoid ,
r <- routesC rel z y (x:avoid) ]
-- Case study: Parsing expressions
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- See under case studies for parsing and the calculator..
-- Infinite lists
-- ^^^^^^^^^^^^^^
-- The infinite list of ones.
ones :: [Int]
ones = 1 : ones
-- Add the first two elements of a list.
addFirstTwo :: [Int] -> Int
addFirstTwo (x:y:zs) = x+y
-- Example, applied to ones.
infEx1 = addFirstTwo ones
-- Arithmetic progressions
from :: Int -> [Int]
from n = n : from (n+1)
fromStep :: Int -> Int -> [Int]
fromStep n m = n : fromStep (n+m) m
-- and an example.
infEx2 = fromStep 3 2
-- Infinite list comprehensions.
-- Pythagorean triples
pythagTriples =
[ (x,y,z) | z <- [2 .. ] , y <- [2 .. z-1] ,
x <- [2 .. y-1] , x*x + y*y == z*z ]
-- The powers of an integer
powers :: Int -> [Int]
powers n = [ n^x | x <- [0 .. ] ]
-- Iterating a function (from the Prelude)
-- iterate :: (a -> a) -> a -> [a]
-- iterate f x = x : iterate f (f x)
-- Sieve of Eratosthenes
primes :: [Int]
primes = sieve [2 .. ]
sieve (x:xs) = x : sieve [ y | y <- xs , y `mod` x > 0]
-- Membership of an ordered list.
memberOrd :: Ord a => [a] -> a -> Bool
memberOrd (x:xs) n
| x<n = memberOrd xs n
| x==n = True
| otherwise = False
-- Example: Generating random numbers
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- Find the next (pseudo-)random number in the sequence.
nextRand :: Int -> Int
nextRand n = (multiplier*n + increment) `mod` modulus
-- A (pseudo-)random sequence is given by iterating this function,
randomSequence :: Int -> [Int]
randomSequence = iterate nextRand
-- Suitable values for the constants.
seed, multiplier, increment, modulus :: Int
seed = 17489
multiplier = 25173
increment = 13849
modulus = 65536
-- Scaling the numbers to come in the (integer) range a to b (inclusive).
scaleSequence :: Int -> Int -> [Int] -> [Int]
scaleSequence s t
= map scale
where
scale n = n `div` denom + s
range = t-s+1
denom = modulus `div` range
-- Turn a distribution into a function.
makeFunction :: [(a,Double)] -> (Double -> a)
makeFunction dist = makeFun dist 0.0
makeFun ((ob,p):dist) nLast rand
| nNext >= rand && rand > nLast
= ob
| otherwise
= makeFun dist nNext rand
where
nNext = p*fromInt modulus + nLast
-- Random numbers from 1 to 6 according to the example distribution, dist.
randomTimes = map (makeFunction dist . fromInt) (randomSequence seed)
-- The distribution in question
dist = [(1,0.2), (2,0.25), (3,0.25), (4,0.15), (5,0.1), (6,0.05)]
-- A pitfall of infinite list generators
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- An incorrect Pythagorean triples program.
pythagTriples2
= [ (x,y,z) | x <- [2 .. ] ,
y <- [x+1 .. ] ,
z <- [y+1 .. ] ,
x*x + y*y == z*z ]
-- Why infinite lists?
-- ^^^^^^^^^^^^^^^^^^^
-- Running sums of a list of numbers.
listSums :: [Int] -> [Int]
listSums iList = out
where
out = 0 : zipWith (+) iList out
-- We give a calculation of an example now.
listSumsEx = listSums [1 .. ]
-- Another definition of listSums which uses scanl1', a generalisation of the
-- original function.
listSums' = scanl1' (+) 0
-- A function which combines values from the list
-- using the function f, and whose first output is st.
scanl1' :: (a -> b -> b) -> b -> [a] -> [b]
scanl1' f st iList
= out
where
out = st : zipWith f iList out
-- Factorial Values
facVals = scanl1' (*) 1 [1 .. ]
-- Case study: Simulation
-- ^^^^^^^^^^^^^^^^^^^^^^
-- See case studies.
-- Two factorial lists
-- ^^^^^^^^^^^^^^^^^^^
-- The factorial function
fac :: Int -> Int
fac 0 = 1
fac m = m * fac (m-1)
--
-- Two factorial lists
facMap, facs :: [Int]
facMap = map fac [0 .. ]
facs = 1 : zipWith (*) [1 .. ] facs