fix markup
[lambda.git] / exercises / assignment4.mdwn
1 ## Fixed points ##
2
3 1.  Recall that `ω ≡ \x. x x`, and `Ω ≡ ω ω`.  Is `Ω` a fixed point for `ω`?  Find a fixed point for `ω`, and prove that it is a fixed point.
4
5 2.  Consider `Ω ξ` for an arbitrary term `ξ`.
6 `Ω` is so busy reducing itself (the eternal narcissist) that it
7 never gets around to noticing whether it has an argument, let alone
8 doing anything with that argument.  If so, how could `Ω` have a
9 fixed point?  That is, how could there be an `ξ` such that
10 `Ω ξ <~~> ξ`?  To answer this
11 question, begin by constructing `Y Ω`.  Prove that 
12 `Y Ω` is a fixed point for `Ω`.
13
14 3.  Find two different terms that have the same fixed point.  That is,
15 find terms `F`, `G`, and `ξ` such that `F ξ <~~> ξ` and `G ξ
16 <~~> ξ`.  (If you need a hint, reread the notes on fixed
17 points.)
18
19 4.  Assume that `Ψ` is some fixed point combinator; we're not telling you which one. (You can just write `Psi` in your homework if you don't know how to generate the symbol `Ψ`.) Prove that `Ψ Ψ` is a fixed point of itself, that is, that `Ψ Ψ <~~> Ψ Ψ (Ψ Ψ)`.
20
21 <!-- Proof: YY ~~> Y(YY) ~~> YY(Y(YY)); YY(YY) ~~> YY(Y(YY)) -->
22
23
24 ## Writing recursive functions ##
25
26 5.  Helping yourself to the functions given below,
27 write a recursive function called `fact` that computes the factorial.
28 The factorial `n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1`.
29 For instance, `fact 0 ~~> 1`, `fact 1 ~~> 1`, `fact 2 ~~> 2`, `fact 3 ~~>
30 6`, and `fact 4 ~~> 24`.
31
32         let true = \y n. y in
33         let false = \y n. n in
34         let pair = \a b. \v. v a b in
35         let fst = \a b. a in   ; aka true
36         let snd = \a b. b in   ; aka false
37         let zero = \s z. z in
38         let succ = \n s z. s (n s z) in
39         let zero? = \n. n (\p. false) true in
40         let pred = \n. n (\p. p (\a b. pair (succ a) a)) (pair zero zero) snd in
41         let add = \l r. r succ l in
42         let mult = \l r. r (add l) 0 in
43         let Y = \h. (\u. h (u u)) (\u. h (u u)) in
44
45         let fact = ... in
46
47         fact 4
48
49 6.  For this question, we want to implement **sets** of numbers in terms of lists of numbers, where we make sure as we construct those lists that they never contain a single number more than once. (It would be even more efficient if we made sure that the lists were always sorted, but we won't try to implement that refinement here.) To enforce the idea of modularity, let's suppose you don't know the details of how the lists are implemented. You just are given the functions defined below for them (but pretend you don't see the actual definitions). These define lists in terms of [[one of the new encodings discussed last week|/topics/week3_lists#v5-lists]].
50
51         ; all functions from the previous question, plus
52         ; `num_cmp x y lt eq gt` returns lt when x<y, eq when x==y, gt when x>y
53         let num_cmp = (\base build consume. \l r. r consume (l build base) fst)
54                 ; where base is
55                 (pair (\a b c. b) (K (\a b c. a)))
56                 ; and build is
57                 (\p. pair (\a b c. c) p)
58                 ; and consume is
59                 (\p. p fst p (p snd) (p snd)) in
60         let num_equal? = \x y. num_cmp x y false true false in
61         let neg = \b y n. b n y in
62         let empty = \f n. n in
63         let cons = \x xs. \f n. f x xs in
64         let empty? = \xs. xs (\y ys. false) true in
65         let head = \xs. xs (\y ys. y) err in
66         let tail = \xs. xs (\y ys. ys) empty in
67         let append = Y (\append. \xs zs. xs (\y ys. (cons y (append ys zs))) zs) in
68         let take_while = Y (\take_while. \p xs. xs (\y ys. (p y) (cons y (take_while p ys)) empty) empty) in
69         let drop_while = Y (\drop_while. \p xs. xs (\y ys. (p y) (drop_while p ys) xs) empty) in
70         ...
71         
72     The functions `take_while` and `drop_while` work as described in [[Week 1's homework|assignment1]].
73
74     Using those resources, define a `set_cons` and a `set_equal?` function. The first should take a number argument `x` and a set argument `xs` (implemented as a list of numbers assumed to have no repeating elements), and return a (possibly new) set argument which contains `x`. (But make sure `x` doesn't appear in the result twice!) The `set_equal?` function should take two set arguments `xs` and `ys` and say whether they represent the same set. (Be careful, the lists `[1, 2]` and `[2, 1]` are different lists but do represent the same set. Hence, you can't just use the `list_equal?` function you defined in last week's homework.)
75
76     Here are some tips for getting started. Use `drop_while`, `num_equal?`, and `empty?` to define a `mem?` function that returns `true` if number `x` is a member of a list of numbers `xs`, else returns `false`. Also use `take_while`, `drop_while`, `num_equal?`, `tail` and `append` to define a `without` function that returns a copy of a list of numbers `xs` that omits the first occurrence of a number `x`, if there be such. You may find these functions `mem?` and `without` useful in defining `set_cons` and `set_equal?`. Also, for `set_equal?`, you are probably going to want to define the function recursively... as now you know how to do.
77
78     Some comments comparing this exercise to *The Little Schemer*, and Scheme more generally:
79
80     *   The `set_equal?` you're trying to define here is like `eqset?` in Chapter 7 of *The Little Schemer*, and `set_cons x xs` would be like `(makeset (cons x xs))`, from that same chapter.
81     *   `mem?` and `without` are like the `member?` and `rember` functions defined in Chapter 2 and 3 of *The Little Schemer*, though those functions are defined for lists of symbolic atoms, and here you are instead defining them for lists of numbers.  *The Little Schemer* also defines `multirember`, which removes all occurrences of a match rather than just the first; and `member*` and `rember*` in Chapter 5, that operate on lists that may contain other, embedded lists.
82     *   The native Scheme function that most resembles the `mem?` you're defining is `memv`, though that is defined for more than just numbers, and when that `memv` finds a match it returns a *list* starting with the match, rather than `#t`.
83
84
85 7.  Linguists often analyze natural language expressions into **trees**. We'll need trees in future weeks, and tree structures provide good opportunities for learning how to write recursive functions. Making use of our current resources, we might approximate trees as follows. Instead of words or syntactic categories, we'll have the nodes of the tree labeled with Church numbers. We'll think of a tree as a list in which each element is itself a tree. For simplicity, we'll adopt the convention that a tree of length 1 must contain a number as its only element.
86
87     Then we have the following representations:
88
89               .   
90              /|\  
91             / | \ 
92             1 2  3
93
94         [[1], [2], [3]]
95
96                .  
97               / \ 
98              /\  3
99             1  2  
100
101         [[[1], [2]], [3]]
102
103               .
104              / \
105             1  /\
106               2  3
107
108         [[1], [[2], [3]]]
109
110     Some limitations of this scheme: there is no easy way to label an inner, branching node (for example with a syntactic category like VP), and there is no way to represent a tree in which a mother node has a single daughter.
111
112     When processing a tree, you can test for whether the tree is a leaf node (that is, contains only a single number), by testing whether the length of the list is 1. This will be your base case for your recursive definitions that work on these trees. (You'll probably want to write a function `leaf?` that encapsulates this check.)
113
114     Your assignment is to write a Lambda Calculus function that expects a tree, encoded in the way just described, as an argument, and returns the sum of its leaves as a result. So for all of the trees listed above, it should return `1 + 2 + 3`, namely `6`. You can use any Lambda Calculus implementation of lists you like.
115
116
117
118 8.    The **fringe** of a leaf-labeled tree is the list of values at its leaves, ordered from left-to-right. For example, the fringe of all three trees displayed above is the same list, `[1, 2, 3]`. We are going to return to the question of how to tell whether trees have the same fringe several times this course. We'll discover more interesting and more efficient ways to do it as our conceptual toolboxes get fuller. For now, we're going to explore the straightforward strategy. Write a function that expects a tree as an argument, and returns the list which is its fringe. Next write a function that expects two trees as arguments, converts each of them into their fringes, and then determines whether the two lists so produced are equal. (Convert your `list_equal?` function from last week's homework into the Lambda Calculus for this last step.)
119
120
121
122 ## Arithmetic infinity? ##
123
124 The next few questions involve reasoning about Church arithmetic and
125 infinity.  Let's choose some arithmetic functions:
126
127     succ = \n s z. s (n s z)
128     add = \l r. r succ l in
129     mult = \l r. r (add l) 0 in
130     exp = \base r. r (mult base) 1 in
131
132 There is a pleasing pattern here: addition is defined in terms of
133 the successor function, multiplication is defined in terms of
134 addition, and exponentiation is defined in terms of multiplication.
135
136
137 9.  Find a fixed point `ξ` for the successor function.  Prove it's a fixed
138 point, i.e., demonstrate that `succ ξ <~~> ξ`.  
139
140     We've had surprising success embedding normal arithmetic in the Lambda
141 Calculus, modeling the natural numbers, addition, multiplication, and
142 so on.  But one thing that some versions of arithmetic supply is a
143 notion of infinity, which we'll write as `inf`.  This object sometimes
144 satisfies the following constraints, for any finite natural number `n`:
145
146         n + inf == inf
147         n * inf == inf
148         n ^ inf == inf
149         leq n inf == true
150
151     (Note, though, that with *some* notions of infinite numbers, like [[!wikipedia ordinal numbers]], operations like `+` are defined in such a way that `inf + n` is different from `n + inf`, and does exceed `inf`; similarly for `*` and `^`. With other notions of infinite numbers, like the [[!wikipedia cardinal numbers]], even less familiar arithmetic operations are employed.)
152
153 10. Prove that `add ξ 1 <~~> ξ`, where `ξ` is the fixed
154 point you found in (1).  What about `add ξ 2 <~~> ξ`?  
155
156 Comment: a fixed point for the successor function is an object such that it
157 is unchanged after adding 1 to it.  It makes a certain amount of sense
158 to use this object to model arithmetic infinity.  For instance,
159 depending on implementation details, it might happen that `leq n ξ` is
160 true for all (finite) natural numbers `n`.  However, the fixed point
161 you found for `succ` and `(+n)` (recall this is shorthand for `\x. add x n`) may not be a fixed point for `(*n)`, for example.
162
163
164 ## Mutually-recursive functions ##
165
166 11. (Challenging.) One way to define the function `even?` is to have it hand off
167 part of the work to another function `odd?`:
168
169         let even? = \x. (zero? x)
170                         ; if x == 0 then result is
171                         true
172                         ; else result turns on whether x-1 is odd
173                         (odd? (pred x))
174
175     At the same tme, though, it's natural to define `odd?` in such a way that it
176 hands off part of the work to `even?`:
177
178         let odd? = \x. (zero? x)
179                        ; if x == 0 then result is
180                        false
181                        ; else result turns on whether x-1 is even
182                        (even? (pred x))
183
184     Such a definition of `even?` and `odd?` is called **mutually recursive**. If you
185 trace through the evaluation of some sample numerical arguments, you can see
186 that eventually we'll always reach a base step. So the recursion should be
187 perfectly well-grounded:
188
189         even? 3
190         ~~> (zero? 3) true (odd? (pred 3))
191         ~~> odd? 2
192         ~~> (zero? 2) false (even? (pred 2))
193         ~~> even? 1
194         ~~> (zero? 1) true (odd? (pred 1))
195         ~~> odd? 0
196         ~~> (zero? 0) false (even? (pred 0))
197         ~~> false
198
199     But we don't yet know how to implement this kind of recursion in the Lambda
200 Calculus.
201
202     The fixed point operators we've been working with so far worked like this:
203
204         let ξ = Y h in
205         ξ <~~> h ξ
206
207     Suppose we had a pair of fixed point operators, `Y1` and `Y2`, that operated on
208 a *pair* of functions `h` and `g`, as follows:
209
210         let ξ1 = Y1 h g in
211         let ξ2 = Y2 h g in
212         ξ1 <~~> h ξ1 ξ2 and
213         ξ2 <~~> g ξ1 ξ2
214
215     If we gave you such a `Y1` and `Y2`, how would you implement the above
216 definitions of `even?` and `odd?`?
217
218                                         
219 12. (More challenging.) Using our derivation of `Y` from [[this week's notes|topics/week4_fixed_point_combinators#deriving-y]] as a model, construct a pair `Y1` and `Y2` that behave in the way described above.
220
221     Here is one hint to get you started: remember that in the notes, we constructed a fixed point for `h` by evolving it into `H` and using `H H` as `h`'s fixed point. We suggested the thought exercise, how might you instead evolve `h` into some `T` and then use `T T T` as `h`'s fixed point. Try solving this problem first. It may help give you the insights you need to define a `Y1` and `Y2`. [[Here are some hints|assignment4_hint]].