Last active
December 27, 2015 08:39
-
-
Save nabeken/7298275 to your computer and use it in GitHub Desktop.
A tour of Go #70
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" | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
// FIXME: In this way how to close a channel when function returns the last value to terminate a loop | |
func Walk2(t *tree.Tree, ch chan int) { | |
if t.Left != nil { | |
Walk(t.Left, ch) | |
} | |
ch <- t.Value | |
if t.Right != nil { | |
Walk(t.Right, ch) | |
} | |
} | |
// In-order | |
// To close a channel I can't call the function recursively... | |
func Walk(t *tree.Tree, ch chan int) { | |
s := [](*tree.Tree){} | |
for len(s) != 0 || t != nil { | |
if t != nil { | |
s = append(s, t) | |
t = t.Left | |
} else { | |
t, s = s[len(s)-1], s[:len(s)-1] | |
ch <- t.Value | |
t = t.Right | |
} | |
} | |
close(ch) | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
fmt.Println("t1:", t1) | |
fmt.Println("t2:", t2) | |
ch1, ch2 := make(chan int), make(chan int) | |
go func() { | |
Walk(t1, ch1) | |
}() | |
go func() { | |
Walk(t2, ch2) | |
}() | |
for { | |
v1, ok1 := <-ch1 | |
v2, ok2 := <-ch2 | |
// detect Walking is finished | |
if !ok1 || !ok2 { | |
break | |
} | |
// compare v1, v2 | |
if v1 != v2 { | |
return false | |
} | |
} | |
// also returns true when t1 and t1 is empty | |
return true | |
} | |
func main() { | |
ch := make(chan int) | |
t := tree.New(1) | |
fmt.Println(t) | |
go Walk(t, ch) | |
for i := 0; i < 10; i++ { | |
fmt.Println(<-ch) | |
} | |
fmt.Println(Same(&tree.Tree{}, &tree.Tree{})) | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment