-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathChapter12.hs
More file actions
194 lines (137 loc) · 1.69 KB
/
Chapter12.hs
File metadata and controls
194 lines (137 loc) · 1.69 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
module Chapter12 where
-- Lazy Evaluation
-- evaluate an expression when it is needed
inc :: Int -> Int
inc n = n + 1
{-
Eager Evaluation or CBV
inc (2 * 3)
inc 6
6 + 1
7
Lazy Evaluation or CBN
inc (2 * 3)
(2 * 3) + 1
6 + 1
7
-}
{-
This does not hold for most imperative languages
CBN
n = 0
n + (n = 1)
0 + (n = 1)
0 + 1
1
CBV
n = 0
n + (n = 1)
n + 1
1 + 1
2
-}
mult :: (Int, Int) -> Int
mult (x, y) = x * y
{-
CBV
mult (1 + 2, 2 + 3)
mult (3, 2 + 3)
mult (3, 5)
3 * 5
15
CBN
mult (1 + 2, 2 + 3)
(1 + 2) * (2 + 3)
3 * (2 + 3)
3 * 5
15
-}
-- Lambda Expressions
mult' :: Int -> Int -> Int
mult' x = \ y -> x * y
{-
CBV
mult (1 + 2) (2 + 3)
mult 3 (2 + 3)
(\ y -> 3 * y) (2 + 3)
(\ y -> 3 * y) 5
3 * 5
15
CBN
mult (1 + 2) (2 + 3)
(\ y -> (1 + 2) * y) (2 + 3)
(1 + 2) * (2 + 3)
3 * (2 + 3)
3 * 5
15
-}
-- Termination
inf :: Int
inf = 1 + inf
{-
Both CBV and CBN will not terminate
inf
1 + inf
1 + 1 + inf
1 + 1 + 1 + inf
1 + 1 + 1 + 1 + ......
-}
fst' :: (Int, Int) -> Int
fst' (x, _) = x
{-
CBV
fst (0, inf)
fst (0, 1 + inf)
fst (0, 1 + 1 + .....)
CBN
fst (0, inf)
0
-}
-- Number of reductions
square :: Int -> Int
square x = x * x
{-
CBV
square (1 + 2)
square 3
3 * 3
9
CBN
square (1 + 2)
(1 + 2) * (1 + 2)
3 * (1 + 2)
3 * 3
9
-}
-- Infinite Structures
ones :: [Int]
ones = 1 : ones
{-
Both CBV and CBN
ones
1 : ones
1 : 1 : ones
1 : 1 : 1 : ......
CBV
head ones
head (1 : ones)
head (1 : 1 : ones)
head (1 : 1 : 1 : .......)
CBN
head ones
head (1 : ones)
1
take 3 ones
[1, 1, 1]
filter (<= 5) [1..] will not terminate
takeWhile (<= 5) [1..] will terminate
-}
-- Strict Application (using eager evaluation)
{-
use the $! function
square $! (1 + 2)
square $! 3
square 3
3 * 3
9
-}