From 09995b2f4110733f5b6a408001592e56c4471f94 Mon Sep 17 00:00:00 2001 From: "Stephen M. McQuay" Date: Mon, 3 Sep 2012 21:15:50 -0600 Subject: [PATCH] Nested closure solution to Equivalent Binary Tree Walk method --- exercises/08-ebt/go.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 exercises/08-ebt/go.go diff --git a/exercises/08-ebt/go.go b/exercises/08-ebt/go.go new file mode 100644 index 0000000..9654635 --- /dev/null +++ b/exercises/08-ebt/go.go @@ -0,0 +1,39 @@ +package main + +import ( + "code.google.com/p/go-tour/tree" + "fmt" +) + +// Walk walks the tree t sending all values +// from the tree to the channel ch. +func Walk(t *tree.Tree, ch chan int) { + // do it as a nested closure so that I can control the call to close so + // that I can use the range-based forloop in main.main + var walk func(t *tree.Tree) + walk = func(t *tree.Tree) { + if t == nil { + return + } + walk(t.Left) + ch <- t.Value + walk(t.Right) + } + walk(t) + close(ch) +} + +// Same determines whether the trees +// t1 and t2 contain the same values. +func Same(t1, t2 *tree.Tree) bool + +func main() { + t := tree.New(1) + ch := make(chan int) + go Walk(t, ch) + fmt.Printf("%v\n", t) + for i := range ch { + fmt.Printf("%d, ", i) + } + fmt.Println() +}