rename topics/_week4_fixed_point_combinator.mdwn to topics/_week4_fixed_point_combina...
[lambda.git] / exercises / assignment2_answers.mdwn
1 Syntax
2 ------
3
4 Insert all the implicit `( )`s and <code>&lambda;</code>s into the following abbreviated expressions. Don't just insert them *freely*; rather, provide the official expression, without any notational shortcuts, that is syntactically identical to the form presented.
5
6 *In response to your feedback and questions, we refined the explanation of the conventions governing the use of the `.` shorthand. Thanks!*
7
8 1.  `x x (x x x) x`  
9      <code><b>(((</b>x x<b>)</b> (<b>(</b>x x<b>)</b> x)<b>)</b> x<b>)</b></code>
10 2.  `v w (\x y. v x)`  
11     <code><b>((</b>v w<b>)</b> (\x <b>(\</b>y <b>(</b>v x<b>))</b>)<b>)</b></code>
12 3.  `(\x y. x) u v`  
13     <code><b>((</b>(\x <b>(\</b>y x<b>)</b>) u<b>)</b> v<b>)</b></code>
14 4.  `w (\x y z. x z (y z)) u v`  
15     <code><b>(((</b>w (\x <b>(\</b>y <b>(\</b>z <b>((</b>x z<b>)</b> (y z)<b>)))</b>)<b>)</b> u<b>)</b> v<b>)</b></code>
16
17 Mark all occurrences of `(x y)` in the following terms:
18
19 5.  <code>(\x y. <u>x y</u>) x y</code>
20 6.  <code>(\x y. <u>x y</u>) (<u>x y</u>)</code>
21 7.  <code>\x y. <u>x y</u> (<u>x y</u>)</code>
22
23 Reduction
24 ---------
25
26 Find "normal forms" for the following---that is, reduce them until no more reductions are possible. As mentioned in the notes, we'll write <code>&lambda;x</code> as `\x`. If we ever say "reduce" without qualifications, we mean just "beta-reduce" (as opposed to "(beta + eta)-reduce").
27
28 8.  `(\x \y. y x) z` ~~> `\y. y z`
29 9.  `(\x (x x)) z` ~~> `z z`
30 10. `(\x (\x x)) z` ~~> `\x x`
31 11. `(\x (\z x)) z` ~~> `\y z`, be sure to change `\z` to a different variable so as not to "capture" `z`
32 12. `(\x (x (\y y))) (\z (z z))` ~~> `\y y`
33 13. `(\x (x x)) (\x (x x))`  umm..., reductions will forever be possible, they just don't "do" much
34 14. `(\x (x x x)) (\x (x x x))`  that's just mean
35
36
37
38 Booleans
39 --------
40
41 For these questions, and the ones on triples below, we're setting them up so as to encourage you to experiment with Racket and to formulate your answer in Scheme/Racket syntax. But you can answer in Lambda Calculus syntax if you prefer.
42
43 Recall our definitions of true and false.
44
45 >   **true** is defined to be `\t f. t`  
46 >   **false** is defined to be `\t f. f`
47
48 In Racket, these functions can be defined like this:
49
50     (define true (lambda (t) (lambda (f) t)))
51     (define false (lambda (t) (lambda (f) f)))
52
53 (Note that they are different from Racket's *primitive* boolean values `#t` and `#f`.)
54
55
56 15. Define a `neg` operator that negates `true` and `false`.
57
58     Expected behavior:
59
60         (((neg true) 10) 20)
61
62     evaluates to `20`, and
63
64         (((neg false) 10) 20)
65
66     evaluates to `10`.
67
68         (define neg (lambda (p) ((p false) true)))
69
70 16. Define an `or` operator.
71
72         (define or (lambda (p) (lambda (q) ((p p) q))))
73
74     or:
75
76         (define or (lambda (p) (lambda (q) ((p true) q))))
77
78
79 17. Define an `xor` operator. If you haven't seen this term before, here's a truth table:
80
81         true   xor  true   == false
82         true   xor  false  == true
83         false  xor  true   == true
84         false  xor  false  == false
85
86     <!-- -->
87
88         (define xor (lambda (p) (lambda (q) ((p (neg q)) q))))
89
90
91 Triples
92 -------
93
94 Recall our definitions of ordered triples.
95
96 >   the triple **(**a**, **b**, **c**)** is defined to be `\f. f a b c`
97
98 To extract the first element of a triple `t`, you write:
99
100     t (\fst snd trd. fst)
101
102 Here are some definitions in Racket:
103
104     (define make-triple  (lambda (fst) (lambda (snd) (lambda (trd) (lambda (f) (((f fst) snd) trd))))))
105     (define fst_of_three (lambda (fst) (lambda (snd) (lambda (trd) fst))))
106     (define snd_of_three (lambda (fst) (lambda (snd) (lambda (trd) snd))))
107
108 Now we can write:
109
110     (define t (((make-triple 10) 20) 30))
111     (t fst_of_three)  ; will evaluate to 10
112     (t snd_of_three)  ; will evaluate to 20
113
114 If you're puzzled by having the triple to the left and the function that
115 operates on it come second, think about why it's being done this way: the triple
116 is a package that takes a function for operating on its elements *as an
117 argument*, and returns *the result of* operating on its elements with that
118 function. In other words, the triple is a higher-order function.
119
120
121 18. Define the `swap12` function that permutes the elements of a triple. Expected behavior:
122
123         (define t (((make-triple 10) 20) 30))
124         ((t swap12) fst_of_three) ; evaluates to 20
125         ((t swap12) snd_of_three) ; evaluates to 10
126
127     Write out the definition of `swap12` in Racket.
128
129         (define swap12 (lambda (x) (lambda (y) (lambda (z)
130                          (lambda (f) (((f y) x) z))))))
131
132
133 19. Define a `dup3` function that duplicates its argument to form a triple
134 whose elements are the same.  Expected behavior:
135
136         ((dup3 10) fst_of_three) ; evaluates to 10
137         ((dup3 10) snd_of_three) ; evaluates to 10
138
139     <!-- -->
140
141         (define dup3 (lambda (x)
142                        (lambda (f) (((f x) x) x))))
143
144 20. Define a `dup27` function that makes
145 twenty-seven copies of its argument (and stores them in a data structure of
146 your choice).
147
148     OK, then we will store them in a triply-nested triple:
149
150         (define dup27 (lambda (x) (dup3 (dup3 (dup3 x)))))
151
152 Folds and Lists
153 ---------------
154
155 21. Using Kapulet syntax, define `fold_left`.
156
157         # fold_left (f, z) [a, b, c] == f (f (f z a) b) c
158         letrec
159           fold_left (f, z) xs = case xs of
160                                   []       then z;
161                                   x' & xs' then fold_left (f, f (z, x')) xs'
162                                 end
163         in fold_left
164
165
166 22. Using Kapulet syntax, define `filter` (problem 7 in last week's homework) in terms of `fold_right` and other primitive syntax like `lambda`, `&`, and `[]`. Don't use `letrec`! All the `letrec`-ing that happens should come from the one inside the definition of `fold_right`.
167
168         let
169           filter (p, xs) = fold_right ((lambda (y, ys). if p y then y & ys else ys), []) xs
170         in filter
171
172 23. Using Kapulet syntax, define `&&` in terms of `fold_right`. (To avoid trickiness about the infix syntax, just call it `append`.) As with problem 22 (the previous problem), don't use `letrec`!
173
174         let
175           xs && ys = fold_right ((&), ys) xs
176           # or append (xs, ys) = ...
177         in (&&)
178
179 24. Using Kapulet syntax, define `head` in terms of `fold_right`. When applied to a non-empty list, it should give us the first element of that list. When applied to an empty list, let's say it should give us `'err`. As with problem 22, don't use `letrec`!
180
181         let
182           head xs = fold_right ((lambda (y, _). y), 'err) xs
183         in head
184
185 25. We mentioned in the Encoding notes that `fold_left (flipped_cons, []) xs` would give us the elements of `xs` but in the reverse order. So that's how we can express `reverse` in terms of `fold_left`. How would you express `reverse` in terms of `fold_right`? As with problem 22, don't use `letrec`!
186
187     *Here is a boring, inefficient answer*
188
189         let
190           append (ys, zs) = fold_right ((&), zs) ys;  # aka (&&)
191           f (y, prev) = append (prev, [y]);
192           reverse xs = fold_right (f, []) xs
193         in reverse
194
195     or (same basic idea, just written differently):
196
197         let
198           f (y, prev) = fold_right ((&), [y]) prev;
199           reverse xs = fold_right (f, []) xs
200         in reverse
201
202     *Here is an elegant, efficient answer following the [[hint|assignment2 hint]]*
203
204     Suppose the list we want to reverse is `[10, 20, 30]`. Applying `fold_right` to this will begin by computing `f (30, z)` for some `f` and `z` that we specify. If we made the result of that be something like `30 & blah`, or any larger structure that contained something of that form, it's not clear how we could, using just the resources of `fold_right`, reach down into that structure and replace the `blah` with some other element, as we'd evidently need to, since after the next step we should get `30 & (20 & blah)`. What we'd like instead is something like this:
205
206         30 & < >
207
208     Where `< >` isn't some *value* but rather a *hole*. Then with the next step, we want to plug into that hole `20 & < >`, which contains its own hole. Getting:
209
210         30 & (20 & < >)
211
212     And so on. That is the key to the solution. The questions you need to answer, to turn this into something executable, are:
213
214     1.  What is a hole? How can we implement it?
215
216         A hole is a bound variable. `30 & < >` is `lambda x. 30 & x`.
217
218     2.  What should `f` be, so that the result of the second step, namely `f (20, 30 & < >)`, is `30 & (20 & < >)`?
219
220             let
221               f (y, prev) = lambda x. prev (y & x)
222             in ...
223
224     3.  Given that choice of `f`, what should `z` be, so that the result of the first step, namely `f (30, z)` is `30 & < >`?
225
226         The identity function: `f (30, (lambda y. y))` will reduce to `lambda x. (lambda y. y) (30 & x)`, which will reduce to `lambda x. 30 & x`.
227
228     4.  At the end of the `fold_right`, we're going to end with something like `30 & (20 & (10 & < >))`. But what we want is `[30, 20, 10]`. How can we turn what we've gotten into what we want?
229
230         Supply it with `[]` as an argument.
231
232     5.  So now put it all together, and explain how to express `reverse xs` using `fold_right` and primitive syntax like `lambda`, `&`, and `[]`?
233
234             let
235               f (y, prev) = lambda x. prev (y & x);
236               id match lambda y. y;
237               reverse xs = (fold_right (f, id) xs) []
238             in reverse
239
240 Numbers
241 -------
242
243 26. Given that we've agreed to Church's encoding of the numbers:
244
245     <code>0 &equiv; \f z. z</code>  
246     <code>1 &equiv; \f z. f z</code>  
247     <code>2 &equiv; \f z. f (f z)</code>  
248     <code>3 &equiv; \f z. f (f (f z))</code>  
249     <code>...</code>
250
251     How would you express the `succ` function in the Lambda Calculus?
252
253         let succ = \n. \f z. f (n f z) in ...
254
255     Compare the definition of `cons`, which has an additional element:
256
257     <code>let cons = \<u>d</u> ds. \f z. f <u>d</u> (ds f z) in ...</code>