Last active
December 20, 2015 00:19
-
-
Save jeremyheiler/6040966 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "code.google.com/p/go-tour/tree" | |
import "fmt" | |
func Walk2(t *tree.Tree, ch chan int) { | |
if t.Left != nil { | |
Walk2(t.Left, ch) | |
} | |
ch <- t.Value | |
if t.Right != nil { | |
Walk2(t.Right, ch) | |
} | |
} | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int) { | |
Walk2(t, ch); | |
close(ch) | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
var ch1 = make(chan int) | |
var ch2 = make(chan int) | |
go Walk(t1, ch1) | |
go Walk(t2, ch2) | |
for { | |
v1, ok1 := <- ch1 | |
v2, ok2 := <- ch2 | |
if !ok1 || !ok2 { | |
return true | |
} | |
if v1 != v2 { | |
return false | |
} | |
} | |
return true | |
} | |
func main() { | |
var tr = tree.New(1) | |
var ch = make(chan int) | |
fmt.Println(tr); | |
go Walk(tr, ch) | |
for i := range ch { | |
fmt.Println(i) | |
} | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
fmt.Println(Same(tree.New(2), tree.New(2))) | |
fmt.Println(Same(tree.New(3), tree.New(2))) | |
} | |
// Result: | |
// ((((1 (2)) 3 (4)) 5 ((6) 7 ((8) 9))) 10) | |
// 1 | |
// 2 | |
// 3 | |
// 4 | |
// 5 | |
// 6 | |
// 7 | |
// 8 | |
// 9 | |
// 10 | |
// true | |
// false | |
// true | |
// false |
Cool; thanks for taking a look! I'm really enjoying having multiple returns. I was just reading about this in Racket, too.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One thing that is a style thing is to have a package doc: comments placed before the
package main
line that is a succinct explanation of what the code does.