1 ## Same-fringe using zippers ##
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):
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.
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:
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.
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.
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.
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:
30 # type blah = Blah of int * int * (char -> bool);;
32 and then having to remember which element in the triple was which:
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)
38 # let b1 = Blah (1, 2, (fun c -> c = 'M'));;
39 val b1 : blah = Blah (1, 2, <fun>)
41 records let you attach descriptive labels to the components of the tuple:
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>}
49 These were the strategies to extract the components of an unlabeled tuple:
51 let h = fst some_pair (* accessor functions fst and snd are only predefined for pairs *)
53 let (h, w, test) = b1 (* works for arbitrary tuples *)
56 | (h, w, test) -> ... (* same as preceding *)
58 Here is how you can extract the components of a labeled record:
60 let h = b2.height (* handy! *)
62 let {height = h; weight = w; char_tester = test} = b2 in
63 (* go on to use h, w, and test ... *)
66 | {height = h; weight = w; char_tester = test} ->
67 (* same as preceding *)
69 Anyway, using record types, we might define the tree zipper interface like so. First, we define a type for leaf-labeled, binary trees:
71 type 'a tree = Leaf of 'a | Node of 'a tree * 'a tree
73 Next, the types for our tree zippers:
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 }
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.
81 The following function takes an `'a tree` and returns an `'a zipper` focused on its root:
83 let new_zipper (t : 'a tree) : 'a zipper =
84 {in_focus = t; context = Root}
86 Here are the beginnings of functions to move from one focused tree to another:
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 *)
96 | Node(left, right) ->
97 move_botleft {in_focus = left; context = Nonroot {up = z.context; left = None; right = Some right}}
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 *)
109 | Nonroot {up; left= None; right = Some right} ->
110 Some {in_focus = right; context = Nonroot {up; left = Some z.in_focus; right = None}}
112 | Nonroot {up; left = Some left; right = None} ->
113 move_right_or_up {in_focus = Node(left, z.in_focus); context = up}
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`.)
120 Having completed that, we can use define a function that enumerates a tree's fringe, step by step, until it's exhausted:
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
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
136 | Some z' -> Some (move_botleft z') in
137 (* return saved label and next_state *)
138 Some (current, next_state)
140 | None -> (* we've finished enumerating the fringe *)
142 (* return the next_leaf function and initial state *)
143 next_leaf, initial_state
145 Here's an example of `make_fringe_enumerator` in action:
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;;
154 val state1' : int zipper option = None
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;;
164 val state2' : int zipper option = Some ...
165 # let Some (res2, state2'') = next2 state2';;
167 val state2'' : int zipper option = Some ...
168 # let Some (res2, state2''') = next2 state2'';;
170 val state2''' : int zipper option = None
172 - : (int * int zipper option) option = None
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.
176 Using these fringe enumerators, we can write our `same_fringe` function like this:
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'
186 loop initial_state1 initial_state2
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.
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.
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.
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:
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 () ->
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
210 | Some z' -> _____ in
211 (* return saved label *)
214 | None -> (* we've finished enumerating the fringe *)
216 (* return the next_leaf function *)
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 ()
229 You should fill in the blanks.
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 () ->
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
246 | Some z' -> Some (move_botleft z') in
247 (* return saved label *)
250 | None -> (* we've finished enumerating the fringe *)
252 (* return the next_leaf function *)
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 ()
266 Here's an example of our new `make_fringe_enumerator` in action:
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>
273 - : int option = Some 1
275 - : int option = None
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>
283 - : int option = Some 1
285 - : int option = Some 2
287 - : int option = Some 3
289 - : int option = None
291 - : int option = None
294 ## Same-fringe using streams ##
296 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.
298 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.
300 So here is a natural OCaml type for a stream. (You could also do things differently.)
302 type 'a stream = End | Next of 'a * (unit -> 'a stream);;
304 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, ...`
306 # let rec make_int_stream i = Next (i, fun () -> make_int_stream (i + 1));;
307 val make_int_stream : int -> int stream = <fun>
309 # let int_stream = make_int_stream 1;;
310 val int_stream : int stream = Next (1, <fun>) (* First element: 1 *)
312 # let tail = match int_stream with Next (i, rest) -> rest;;
313 val tail : unit -> int stream = <fun> (* Tail: a thunk *)
315 (* Force the thunk to compute the second element *)
317 - : int stream = Next (2, <fun>) (* Second element: 2 *)
319 # match tail () with Next (_, rest) -> rest ();;
320 - : int stream = Next (3, <fun>) (* Third element: 3 *)
322 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".
324 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.
326 This code uses Scheme's `cond` construct. That works like this;
329 ((test1 argument argument) result1)
330 ((test2 argument argument) result2)
331 ((test3 argument argument) result3)
336 (if (test1 argument argument)
340 (if (test2 argument argument)
344 (if (test3 argument argument)
350 Some other Scheme details or reminders:
352 * `#t` is true and `#f` is false
353 * `(lambda () ...)` constructs a thunk
354 * there is no difference in meaning between `[...]` and `(...)`; we just sometimes use the square brackets for clarity
355 * `'(1 . 2)` and `(cons 1 2)` are pairs (the same pair)
356 * `(list)` and `'()` both evaluate to the empty list
357 * `(null? lst)` tests whether `lst` is the empty list
358 * non-empty lists are implemented as pairs whose second member is a list
359 * `'()` `'(1)` `'(1 2)` `'(1 2 3)` are all lists
360 * `(list)` `(list 1)` `(list 1 2)` `(list 1 2 3)` are the same lists as the preceding
361 * `'(1 2 3)` and `(cons 1 '(2 3))` are both pairs and lists (the same list)
362 * `(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
363 * `(car lst)` extracts the first member of a pair / head of a list
364 * `(cdr lst)` extracts the second member of a pair / tail of a list
370 4. Here is the Scheme code handling the same-fringe problem. You should fill in the blanks:
372 (define (lazy-flatten tree)
373 (letrec ([helper (lambda (tree tail-thunk)
376 (helper (car tree) (lambda () (helper _____ tail-thunk)))]
377 [else (cons tree tail-thunk)]))])
378 (helper tree (lambda () _____))))
380 (define (stream-equal? stream1 stream2)
382 [(and (null? stream1) (null? stream2)) _____]
383 [(and (pair? stream1) (pair? stream2))
384 (and (equal? (car stream1) (car stream2))
388 (define (same-fringe? tree1 tree2)
389 (stream-equal? (lazy-flatten tree1) (lazy-flatten tree2)))
391 (define tree1 '(((1 . 2) . (3 . 4)) . (5 . 6)))
392 (define tree2 '(1 . (((2 . 3) . (4 . 5)) . 6)))
394 (same-fringe? tree1 tree2)