add Unreliable Guide OCaml Modules
[lambda.git] / exercises / assignment12.mdwn
1 ## Same-fringe using zippers ##
2
3 Recall back in [[Assignment 4|assignment4#fringe]], we asked you to enumerate the "fringe" of a leaf-labeled tree. Both of these trees (here I *am* drawing the labels in the diagram):
4
5         .                .
6        / \              / \
7       .   3            1   .
8      / \                  / \
9     1   2                2   3
10
11 have the same fringe: `[1; 2; 3]`. We also asked you to write a function that determined when two trees have the same fringe. The way you approached that back then was to enumerate each tree's fringe, and then compare the two lists for equality. Today, and then again in a later class, we'll encounter new ways to approach the problem of determining when two trees have the same fringe.
12
13
14 Supposing you did work out an implementation of the tree zipper, then one way to determine whether two trees have the same fringe would be: go downwards (and leftwards) in each tree as far as possible. Compare the focused leaves. If they're different, stop because the trees have different fringes. If they're the same, then for each tree, move rightward if possible; if it's not (because you're at the rightmost leaf in a subtree), move upwards then try again to move rightwards. Repeat until you are able to move rightwards. Once you do move rightwards, go downwards (and leftwards) as far as possible. Then you'll be focused on the next leaf in the tree's fringe. The operations it takes to get to "the next leaf" may be different for the two trees. For example, in these trees:
15
16         .                .
17        / \              / \
18       .   3            1   .
19      / \                  / \
20     1   2                2   3
21
22 you won't move upwards at the same steps. Keep comparing "the next leaves" until they are different, or you exhaust the leaves of only one of the trees (then again the trees have different fringes), or you exhaust the leaves of both trees at the same time, without having found leaves with different labels. In this last case, the trees have the same fringe.
23
24 If your trees are very big---say, millions of leaves---you can imagine how this would be quicker and more memory-efficient than traversing each tree to construct a list of its fringe, and then comparing the two lists so built to see if they're equal. For one thing, the zipper method can abort early if the fringes diverge early, without needing to traverse or build a list containing the rest of each tree's fringe.
25
26 Let's sketch the implementation of this. We won't provide all the details for an implementation of the tree zipper (you'll need to fill those in), but we will sketch an interface for it.
27
28 In these exercises, we'll help ourselves to OCaml's **record types**. These are nothing more than tuples with a pretty interface. Instead of saying:
29
30     # type blah = Blah of int * int * (char -> bool);;
31
32 and then having to remember which element in the triple was which:
33
34     # let b1 = Blah (1, (fun c -> c = 'M'), 2);;
35     Error: This expression has type int * (char -> bool) * int
36     but an expression was expected of type int * int * (char -> bool)
37     # (* damnit *)
38     # let b1 = Blah (1, 2, (fun c -> c = 'M'));;
39     val b1 : blah = Blah (1, 2, <fun>)
40
41 records let you attach descriptive labels to the components of the tuple:
42
43     # type blah_record = { height : int; weight : int; char_tester : char -> bool };;
44     # let b2 = { height = 1; weight = 2; char_tester = (fun c -> c = 'M') };;
45     val b2 : blah_record = {height = 1; weight = 2; char_tester = <fun>}
46     # let b3 = { height = 1; char_tester = (fun c -> c = 'K'); weight = 3 };; (* also works *)
47     val b3 : blah_record = {height = 1; weight = 3; char_tester = <fun>}
48
49 These were the strategies to extract the components of an unlabeled tuple:
50
51     let h = fst some_pair (* accessor functions fst and snd are only predefined for pairs *)
52
53     let (h, w, test) = b1 (* works for arbitrary tuples *)
54
55     match b1 with
56     | (h, w, test) -> ... (* same as preceding *)
57
58 Here is how you can extract the components of a labeled record:
59
60     let h = b2.height (* handy! *)
61
62     let {height = h; weight = w; char_tester = test} = b2 in
63     (* go on to use h, w, and test ... *)
64
65     match test with
66     | {height = h; weight = w; char_tester = test} ->
67     (* same as preceding *)
68
69 Anyway, using record types, we might define the tree zipper interface like so. First, we define a type for leaf-labeled, binary trees:
70
71     type 'a tree = Leaf of 'a | Node of 'a tree * 'a tree
72
73 Next, the types for our tree zippers:
74
75     type 'a zipper = { in_focus: 'a tree; context : 'a context }
76     and 'a context = Root | Nonroot of 'a nonroot_context
77     and 'a nonroot_context = { up : 'a context; left: 'a tree option; right: 'a tree option }
78
79 Unlike in seminar, here we represent the siblings as `'a tree option`s rather than `'a tree list`s. Since we're dealing with binary trees, each context will have exactly one sibling, either to the right or to the left.
80
81 The following function takes an `'a tree` and returns an `'a zipper` focused on its root:
82
83     let new_zipper (t : 'a tree) : 'a zipper =
84       {in_focus = t; context = Root}
85
86 Here are the beginnings of functions to move from one focused tree to another:
87
88     let rec move_botleft (z : 'a zipper) : 'a zipper =
89       (* returns z if the focused node in z has no children *)
90       (* else returns move_botleft (zipper which results from moving down from z's focused node to its leftmost child) *)
91       _____ (* YOU SUPPLY THE DEFINITION *)
92
93 <!--
94     match z.in_focus with
95     | Leaf _ -> z
96     | Node(left, right) ->
97         move_botleft {in_focus = left; context = Nonroot {up = z.context; left = None; right = Some right}}
98 -->
99
100
101     let rec move_right_or_up (z : 'a zipper) : 'a zipper option =
102       (* if it's possible to move right in z, returns Some (the result of doing so) *)
103       (* else if it's not possible to move any further up in z, returns None *)
104       (* else returns move_right_or_up (result of moving up in z) *)
105       _____ (* YOU SUPPLY THE DEFINITION *)
106
107 <!--
108     match z.context with
109     | Nonroot {up; left= None; right = Some right} ->
110         Some {in_focus = right; context = Nonroot {up; left = Some z.in_focus; right = None}}
111     | Root -> None
112     | Nonroot {up; left = Some left; right = None} ->
113         move_right_or_up {in_focus = Node(left, z.in_focus); context = up}
114     | _ -> assert false
115 -->
116
117
118 1.  Your first assignment is to complete the definitions of `move_botleft` and `move_right_or_up`. (Really it should be `move_right_or_up_..._and_right`.)
119
120     <a id=enumerate1></a>
121     Having completed that, we can use define a function that enumerates a tree's fringe, step by step, until it's exhausted:
122
123         let make_fringe_enumerator (t: 'a tree) =
124           (* create a zipper focusing the botleft of t *)
125           let zbotleft = move_botleft (new_zipper t) in
126           (* create initial state, pointing to zbotleft *)
127           let initial_state : 'a zipper option = Some zbotleft in
128           (* construct the next_leaf function *)
129           let next_leaf : 'a zipper option -> ('a * 'a zipper option) option =
130             fun state -> match state with
131             | Some z -> (
132               (* extract label of currently-focused leaf *)
133               let Leaf current = z.in_focus in
134               (* create next_state pointing to next leaf, if there is one *)
135               let next_state : 'a zipper option = match move_right_or_up z with
136                 | None -> None
137                 | Some z' -> Some (move_botleft z') in
138               (* return saved label and next_state *)
139               Some (current, next_state)
140               )
141             | None -> (* we've finished enumerating the fringe *)
142               None in
143           (* return the next_leaf function and initial state *)
144           next_leaf, initial_state
145
146     Here's an example of `make_fringe_enumerator` in action:
147
148         # let tree1 = Leaf 1;;
149         val tree1 : int tree = Leaf 1
150         # let next1, state1 = make_fringe_enumerator tree1;;
151         val next1 : int zipper option -> (int * int zipper option) option = <fun>
152         val state1 : int zipper option = Some ...
153         # let Some (res1, state1') = next1 state1;;
154         val res1 : int = 1
155         val state1' : int zipper option = None
156         # next1 state1';;
157         - : (int * int zipper option) option = None
158         # let tree2 = Node (Node (Leaf 1, Leaf 2), Leaf 3);;
159         val tree2 : int tree = Node (Node (Leaf 1, Leaf 2), Leaf 3)
160         # let next2, state2 = make_fringe_enumerator tree2;;
161         val next2 : int zipper option -> (int * int zipper option) option = <fun>
162         val state2 : int zipper option = Some ...
163         # let Some (res2, state2') = next2 state2;;
164         val res2 : int = 1
165         val state2' : int zipper option = Some ...
166         # let Some (res2, state2'') = next2 state2';;
167         val res2 : int = 2
168         val state2'' : int zipper option = Some ...
169         # let Some (res2, state2''') = next2 state2'';;
170         val res2 : int = 3
171         val state2''' : int zipper option = None
172         # next2 state2''';;
173         - : (int * int zipper option) option = None
174
175     You might think of it like this: `make_fringe_enumerator` returns a little subprogram that will keep returning the next leaf in a tree's fringe, in the form `Some ...`, until it gets to the end of the fringe. After that, it will return `None`. The subprogram's memory of where it is and what steps to perform next are stored in the `next_state` variables that are part of its input and output.
176
177     Using these fringe enumerators, we can write our `same_fringe` function like this:
178
179         let same_fringe (t1 : 'a tree) (t2 : 'a tree) : bool =
180           let next1, initial_state1 = make_fringe_enumerator t1 in
181           let next2, initial_state2 = make_fringe_enumerator t2 in
182           let rec loop state1 state2 : bool =
183             match next1 state1, next2 state2 with
184             | Some (a, state1'), Some (b, state2') when a = b -> loop state1' state2'
185             | None, None -> true
186             | _ -> false in
187           loop initial_state1 initial_state2
188
189     The auxiliary `loop` function will keep calling itself recursively until a difference in the fringes has manifested itself---either because one fringe is exhausted before the other, or because the next leaves in the two fringes have different labels. If we get to the end of both fringes at the same time (`next1 state1, next2 state2` matches the pattern `None, None`) then we've established that the trees do have the same fringe.
190
191 2.  Test your implementations of `move_botleft` and `move_right_or_up` against some example trees to see if the resulting `make_fringe_enumerator` and `same_fringe` functions work as expected. Show us some of your tests.
192
193 3.  Now we'll talk about another way to implement the `make_fringe_enumerator` function above (and so too the `same_fringe` function which uses it). Notice that the pattern given above is that the `make_fringe_enumerator` creates a `next_leaf` function and an initial state, and each time you want to advance the `next_leaf` by one step, you do so by calling it with the current state. It will return a leaf label plus a modified state, which you can use when you want to call it again and take another step. All of the `next_leaf` function's memory about where it is in the enumeration is contained in the state. If you saved an old state, took three steps, and then called the `next_leaf` function again with the saved old state, it would be back where it was three steps ago. But in fact, the way we use the `next_leaf` function and state above, there is no back-tracking. Neither do we "fork" any of the states and pursue different forward paths. Their progress is deterministic, and fixed independently of anything that `same_fringe` might do. All that's up to `same_fringe` is to take the decision of when (and whether) to take another step forward.
194
195     Given that usage pattern, it would be appropriate and convenient to make the `next_leaf` function remember its state itself, in a mutable variable. The client function `same_fringe` doesn't need to do anything with, or even be given access to, this variable. Here's how we might write `make_fringe_enumerator` according to this plan:
196 <a id=enumerate2></a>
197
198         let make_fringe_enumerator (t: 'a tree) =
199           (* create a zipper focusing the botleft of t *)
200           let zbotleft = move_botleft (new_zipper t) in
201           (* create a refcell, initially pointing to zbotleft *)
202           let zcell = ref (Some zbotleft) in
203           (* construct the next_leaf function *)
204           let next_leaf : unit -> 'a option = fun () ->
205             match !zcell with
206             | Some z -> (
207               (* extract label of currently-focused leaf *)
208               let Leaf current = z.in_focus in
209               (* update zcell to point to next leaf, if there is one *)
210               let () = zcell := match move_right_or_up z with
211                 | None -> None
212                 | Some z' -> _____ in
213               (* return saved label *)
214               _____
215               )
216             | None -> (* we've finished enumerating the fringe *)
217               None in
218           (* return the next_leaf function *)
219           next_leaf
220
221         let same_fringe (t1 : 'a tree) (t2 : 'a tree) : bool =
222           let next1 = make_fringe_enumerator t1 in
223           let next2 = make_fringe_enumerator t2 in
224           let rec loop () : bool =
225             match _____, _____ with
226             | Some a, Some b when a = b -> loop ()
227             | None, None -> true
228             | _ -> false in
229           loop ()
230
231     You should fill in the blanks.
232
233     <!--
234         let make_fringe_enumerator (t: 'a tree) =
235           (* create a zipper focusing the botleft of t *)
236           let zbotleft = move_botleft (new_zipper t) in
237           (* create refcell, initially pointing to zbotleft *)
238           let zcell = ref (Some zbotleft) in
239           (* construct the next_leaf function *)
240           let next_leaf : unit -> 'a option = fun () ->
241             match !zcell with
242             | Some z -> (
243               (* extract label of currently-focused leaf *)
244               let Leaf current = z.in_focus in
245               (* update zcell to point to next leaf, if there is one *)
246               let () = zcell := match move_right_or_up z with
247                 | None -> None
248                 | Some z' -> Some (move_botleft z') in
249               (* return saved label *)
250               Some current
251               )
252             | None -> (* we've finished enumerating the fringe *)
253               None in
254           (* return the next_leaf function *)
255           next_leaf
256
257         let same_fringe (t1 : 'a tree) (t2 : 'a tree) : bool =
258           let next1 = make_fringe_enumerator t1 in
259           let next2 = make_fringe_enumerator t2 in
260           let rec loop () : bool =
261             match next1 (), next2 () with
262             | Some a, Some b when a = b -> loop ()
263             | None, None -> true
264             | _ -> false in
265           loop ()
266     -->
267
268     Here's an example of our new `make_fringe_enumerator` in action:
269
270         # let tree1 = Leaf 1;;
271         val tree1 : int tree = Leaf 1
272         # let next1 = make_fringe_enumerator tree1;;
273         val next1 : unit -> int option = <fun>
274         # next1 ();;
275         - : int option = Some 1
276         # next1 ();;
277         - : int option = None
278         # next1 ();;
279         - : int option = None
280         # let tree2 = Node (Node (Leaf 1, Leaf 2), Leaf 3);;
281         val tree2 : int tree = Node (Node (Leaf 1, Leaf 2), Leaf 3)
282         # let next2 = make_fringe_enumerator tree2;;
283         val next2 : unit -> int option = <fun>
284         # next2 ();;
285         - : int option = Some 1
286         # next2 ();;
287         - : int option = Some 2
288         # next2 ();;
289         - : int option = Some 3
290         # next2 ();;
291         - : int option = None
292         # next2 ();;
293         - : int option = None
294
295 <a id=streams1></a>
296 ## Same-fringe using streams ##
297
298 Now we'll describe a different way to create "the little subprograms" that we built above with `make_fringe_enumerator`. This code will make use of a data structure called a "stream". A stream is like a list in that it wraps a series of elements of a single type. It differs from a list in that the tail of the series is left uncomputed until needed. We turn the stream off and on by thunking it, nad by forcing the thunk.
299
300 We'll first show how to implement streams in OCaml, so that the types are manifest. But then we'll switch to a Scheme version to do the same-fringe problem. In part because that's how we have the code already written; but also because some later discussion will use the Scheme code as a starting point. In principle, though, we could have used OCaml throughout.
301
302 So here is a natural OCaml type for a stream. (You could also do things differently.)
303
304     type 'a stream = End | Next of 'a * (unit -> 'a stream);;
305
306 We have a special variant called `End` that encodes a stream that contains no (more) elements, analogous to the empty list `[]`. Streams that are not empty contain a first element, paired with a thunked stream representing the rest of the stream. In order to get access to the next element in the stream, we must force the thunk by applying it to `()`. Watch the behavior of this stream in detail. This stream delivers the natural numbers, in order: `1, 2, 3, ...`
307
308     # let rec make_int_stream i = Next (i, fun () -> make_int_stream (i + 1));;
309     val make_int_stream : int -> int stream = <fun>
310
311     # let int_stream = make_int_stream 1;;
312     val int_stream : int stream = Next (1, <fun>)         (* First element: 1 *)
313
314     # let tail = match int_stream with Next (i, rest) -> rest;;
315     val tail : unit -> int stream = <fun>                 (* Tail: a thunk *)
316
317     (* Force the thunk to compute the second element *)
318     # tail ();;
319     - : int stream = Next (2, <fun>)                      (* Second element: 2 *)
320
321     # match tail () with Next (_, rest) -> rest ();;
322     - : int stream = Next (3, <fun>)                      (* Third element: 3 *)
323
324 You can think of `int_stream` as a functional object that provides access to an infinite sequence of integers, one at a time. It's as if we had written `[1;2;...]` where `...` meant "continue for as long as some other process needs new integers".
325
326 Okay, now armed with the idea of a stream, let's use a Scheme version of them to handle the same-fringe problem. This code is taken from <http://c2.com/cgi/wiki?SameFringeProblem>. It uses thunks to delay the evaluation of code that computes the tail of a list of a tree's fringe. It also involves passing "the rest of the enumeration of the fringe" as a thunk argument (`tail-thunk` below). Your assignment is to fill in the blanks in the code, **and also to supply comments to the code,** to explain what every significant piece is doing. Don't forget to supply the comments, this is an important part of the assignment.
327
328 <a id=scheme></a>
329 This code uses Scheme's `cond` construct. That works like this;
330
331     (cond
332         ((test1 argument argument) result1)
333         ((test2 argument argument) result2)
334         ((test3 argument argument) result3)
335         (else result4))
336
337 is equivalent to:
338
339     (if (test1 argument argument)
340        ; then
341          result1
342        ; else
343          (if (test2 argument argument)
344             ; then
345               result2
346             ; else
347               (if (test3 argument argument)
348                  ; then
349                    result3
350                  ; else
351                    result4)))
352
353 Some other Scheme details or reminders:
354
355 *   `#t` is true and `#f` is false
356 *   `(lambda () ...)` constructs a thunk
357 *   there is no difference in meaning between `[...]` and `(...)`; we just sometimes use the square brackets for clarity
358 *   `'(1 . 2)` and `(cons 1 2)` are pairs (the same pair)
359 *   `(list)` and `'()` both evaluate to the empty list
360 *   `(null? lst)` tests whether `lst` is the empty list
361 *   non-empty lists are implemented as pairs whose second member is a list
362 *   `'()` `'(1)` `'(1 2)` `'(1 2 3)` are all lists
363 *   `(list)` `(list 1)` `(list 1 2)` `(list 1 2 3)` are the same lists as the preceding
364 *   `'(1 2 3)` and `(cons 1 '(2 3))` are both pairs and lists (the same list)
365 *   `(pair? lst)` tests whether `lst` is a pair; if `lst` is a non-empty list, it will also pass this test; if `lst` fails this test, it may be because `lst` is the empty list, or because it's not a list or pair at all
366 *   `(car lst)` extracts the first member of a pair / head of a list
367 *   `(cdr lst)` extracts the second member of a pair / tail of a list
368
369 <!-- -->
370
371 <a id=streams2></a>
372
373 4.  Here is the Scheme code handling the same-fringe problem. You should fill in the blanks:
374
375         (define (lazy-flatten tree)
376           (letrec ([helper (lambda (tree tail-thunk)
377                              (cond
378                                [(pair? tree)
379                                  (helper (car tree) (lambda () (helper _____ tail-thunk)))]
380                                [else (cons tree tail-thunk)]))])
381                   (helper tree (lambda () _____))))
382
383         (define (stream-equal? stream1 stream2)
384           (cond
385             [(and (null? stream1) (null? stream2)) _____]
386             [(and (pair? stream1) (pair? stream2))
387               (and (equal? (car stream1) (car stream2))
388                 _____)]
389             [else #f]))
390
391         (define (same-fringe? tree1 tree2)
392           (stream-equal? (lazy-flatten tree1) (lazy-flatten tree2)))
393
394         (define tree1 '(((1 . 2) . (3 . 4)) . (5 . 6)))
395         (define tree2 '(1 . (((2 . 3) . (4 . 5)) . 6)))
396
397         (same-fringe? tree1 tree2)
398