update refunct zippers code
[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     Having completed that, we can use define a function that enumerates a tree's fringe, step by step, until it's exhausted:
121
122         let make_fringe_enumerator (t: 'a tree) =
123           (* create a zipper focusing the botleft of t *)
124           let zbotleft = move_botleft (new_zipper t) in
125           (* create initial state, pointing to zbotleft *)
126           let initial_state : 'a zipper option = Some zbotleft in
127           (* construct the next_leaf function *)
128           let next_leaf : 'a zipper option -> ('a * 'a zipper option) option =
129             fun state -> match state with
130             | Some z -> (
131               (* extract label of currently-focused leaf *)
132               let Leaf current = z.in_focus in
133               (* create next_state pointing to next leaf, if there is one *)
134               let next_state : 'a zipper option = match move_right_or_up z with
135                 | None -> None
136                 | Some z' -> Some (move_botleft z') in
137               (* return saved label and next_state *)
138               Some (current, next_state)
139               )
140             | None -> (* we've finished enumerating the fringe *)
141               None in
142           (* return the next_leaf function and initial state *)
143           next_leaf, initial_state
144
145     Here's an example of `make_fringe_enumerator` in action:
146
147         # let tree1 = Leaf 1;;
148         val tree1 : int tree = Leaf 1
149         # let next1, state1 = make_fringe_enumerator tree1;;
150         val next1 : int zipper option -> (int * int zipper option) option = <fun>
151         val state1 : int zipper option = Some ...
152         # let Some (res1, state1') = next1 state1;;
153         val res1 : int = 1
154         val state1' : int zipper option = None
155         # next1 state1';;
156         - : (int * int zipper option) option = None
157         # let tree2 = Node (Node (Leaf 1, Leaf 2), Leaf 3);;
158         val tree2 : int tree = Node (Node (Leaf 1, Leaf 2), Leaf 3)
159         # let next2, state2 = make_fringe_enumerator tree2;;
160         val next2 : int zipper option -> (int * int zipper option) option = <fun>
161         val state2 : int zipper option = Some ...
162         # let Some (res2, state2') = next2 state2;;
163         val res2 : int = 1
164         val state2' : int zipper option = Some ...
165         # let Some (res2, state2'') = next2 state2';;
166         val res2 : int = 2
167         val state2'' : int zipper option = Some ...
168         # let Some (res2, state2''') = next2 state2'';;
169         val res2 : int = 3
170         val state2''' : int zipper option = None
171         # next2 state2''';;
172         - : (int * int zipper option) option = None
173
174     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.
175
176     Using these fringe enumerators, we can write our `same_fringe` function like this:
177
178         let same_fringe (t1 : 'a tree) (t2 : 'a tree) : bool =
179           let next1, initial_state1 = make_fringe_enumerator t1 in
180           let next2, initial_state2 = make_fringe_enumerator t2 in
181           let rec loop state1 state2 : bool =
182             match next1 state1, next2 state2 with
183             | Some (a, state1'), Some (b, state2') when a = b -> loop state1' state2'
184             | None, None -> true
185             | _ -> false in
186           loop initial_state1 initial_state2
187
188     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.
189
190 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.
191
192 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.
193
194     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:
195
196         let make_fringe_enumerator (t: 'a tree) =
197           (* create a zipper focusing the botleft of t *)
198           let zbotleft = move_botleft (new_zipper t) in
199           (* create a refcell, initially pointing to zbotleft *)
200           let zcell = ref (Some zbotleft) in
201           (* construct the next_leaf function *)
202           let next_leaf : unit -> 'a option = fun () ->
203             match !zcell with
204             | Some z -> (
205               (* extract label of currently-focused leaf *)
206               let Leaf current = z.in_focus in
207               (* update zcell to point to next leaf, if there is one *)
208               let () = zcell := match move_right_or_up z with
209                 | None -> None
210                 | Some z' -> _____ in
211               (* return saved label *)
212               _____
213               )
214             | None -> (* we've finished enumerating the fringe *)
215               None in
216           (* return the next_leaf function *)
217           next_leaf
218
219         let same_fringe (t1 : 'a tree) (t2 : 'a tree) : bool =
220           let next1 = make_fringe_enumerator t1 in
221           let next2 = make_fringe_enumerator t2 in
222           let rec loop () : bool =
223             match _____, _____ with
224             | Some a, Some b when a = b -> loop ()
225             | None, None -> true
226             | _ -> false in
227           loop ()
228
229     You should fill in the blanks.
230
231     <!--
232         let make_fringe_enumerator (t: 'a tree) =
233           (* create a zipper focusing the botleft of t *)
234           let zbotleft = move_botleft (new_zipper t) in
235           (* create refcell, initially pointing to zbotleft *)
236           let zcell = ref (Some zbotleft) in
237           (* construct the next_leaf function *)
238           let next_leaf : unit -> 'a option = fun () ->
239             match !zcell with
240             | Some z -> (
241               (* extract label of currently-focused leaf *)
242               let Leaf current = z.in_focus in
243               (* update zcell to point to next leaf, if there is one *)
244               let () = zcell := match move_right_or_up z with
245                 | None -> None
246                 | Some z' -> Some (move_botleft z') in
247               (* return saved label *)
248               Some current
249               )
250             | None -> (* we've finished enumerating the fringe *)
251               None in
252           (* return the next_leaf function *)
253           next_leaf
254
255         let same_fringe (t1 : 'a tree) (t2 : 'a tree) : bool =
256           let next1 = make_fringe_enumerator t1 in
257           let next2 = make_fringe_enumerator t2 in
258           let rec loop () : bool =
259             match next1 (), next2 () with
260             | Some a, Some b when a = b -> loop ()
261             | None, None -> true
262             | _ -> false in
263           loop ()
264     -->
265
266     Here's an example of our new `make_fringe_enumerator` in action:
267
268         # let tree1 = Leaf 1;;
269         val tree1 : int tree = Leaf 1
270         # let next1 = make_fringe_enumerator tree1;;
271         val next1 : unit -> int option = <fun>
272         # next1 ();;
273         - : int option = Some 1
274         # next1 ();;
275         - : int option = None
276         # next1 ();;
277         - : int option = None
278         # let tree2 = Node (Node (Leaf 1, Leaf 2), Leaf 3);;
279         val tree2 : int tree = Node (Node (Leaf 1, Leaf 2), Leaf 3)
280         # let next2 = make_fringe_enumerator tree2;;
281         val next2 : unit -> int option = <fun>
282         # next2 ();;
283         - : int option = Some 1
284         # next2 ();;
285         - : int option = Some 2
286         # next2 ();;
287         - : int option = Some 3
288         # next2 ();;
289         - : int option = None
290         # next2 ();;
291         - : int option = None
292
293 ## Same-fringe using streams ##
294
295 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.
296
297 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.
298
299 So here is a natural OCaml type for a stream. (You could also do things differently.)
300
301     type 'a stream = End | Next of 'a * (unit -> 'a stream);;
302
303 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, ...`
304
305     # let rec make_int_stream i = Next (i, fun () -> make_int_stream (i + 1));;
306     val make_int_stream : int -> int stream = <fun>
307
308     # let int_stream = make_int_stream 1;;
309     val int_stream : int stream = Next (1, <fun>)         (* First element: 1 *)
310
311     # let tail = match int_stream with Next (i, rest) -> rest;;
312     val tail : unit -> int stream = <fun>                 (* Tail: a thunk *)
313
314     (* Force the thunk to compute the second element *)
315     # tail ();;
316     - : int stream = Next (2, <fun>)                      (* Second element: 2 *)
317
318     # match tail () with Next (_, rest) -> rest ();;
319     - : int stream = Next (3, <fun>)                      (* Third element: 3 *)
320
321 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".
322
323 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.
324
325 This code uses Scheme's `cond` construct. That works like this;
326
327     (cond
328         ((test1 argument argument) result1)
329         ((test2 argument argument) result2)
330         ((test3 argument argument) result3)
331         (else result4))
332
333 is equivalent to:
334
335     (if (test1 argument argument)
336        ; then
337          result1
338        ; else
339          (if (test2 argument argument)
340             ; then
341               result2
342             ; else
343               (if (test3 argument argument)
344                  ; then
345                    result3
346                  ; else
347                    result4)))
348
349 Some other Scheme details or reminders:
350
351 *   `#t` is true and `#f` is false
352 *   `(lambda () ...)` constructs a thunk
353 *   there is no difference in meaning between `[...]` and `(...)`; we just sometimes use the square brackets for clarity
354 *   `'(1 . 2)` and `(cons 1 2)` are pairs (the same pair)
355 *   `(list)` and `'()` both evaluate to the empty list
356 *   `(null? lst)` tests whether `lst` is the empty list
357 *   non-empty lists are implemented as pairs whose second member is a list
358 *   `'()` `'(1)` `'(1 2)` `'(1 2 3)` are all lists
359 *   `(list)` `(list 1)` `(list 1 2)` `(list 1 2 3)` are the same lists as the preceding
360 *   `'(1 2 3)` and `(cons 1 '(2 3))` are both pairs and lists (the same list)
361 *   `(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
362 *   `(car lst)` extracts the first member of a pair / head of a list
363 *   `(cdr lst)` extracts the second member of a pair / tail of a list
364
365 <!-- -->
366
367 4.  Here is the Scheme code handling the same-fringe problem. You should fill in the blanks:
368
369         (define (lazy-flatten tree)
370           (letrec ([helper (lambda (tree tail-thunk)
371                              (cond
372                                [(pair? tree)
373                                  (helper (car tree) (lambda () (helper _____ tail-thunk)))]
374                                [else (cons tree tail-thunk)]))])
375                   (helper tree (lambda () _____))))
376
377         (define (stream-equal? stream1 stream2)
378           (cond
379             [(and (null? stream1) (null? stream2)) _____]
380             [(and (pair? stream1) (pair? stream2))
381               (and (equal? (car stream1) (car stream2))
382                 _____)]
383             [else #f]))
384
385         (define (same-fringe? tree1 tree2)
386           (stream-equal? (lazy-flatten tree1) (lazy-flatten tree2)))
387
388         (define tree1 '(((1 . 2) . (3 . 4)) . (5 . 6)))
389         (define tree2 '(1 . (((2 . 3) . (4 . 5)) . 6)))
390
391         (same-fringe? tree1 tree2)
392