Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created June 5, 2012 21:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanorelli/2878051 to your computer and use it in GitHub Desktop.
Save jordanorelli/2878051 to your computer and use it in GitHub Desktop.
a tree, in go
package main
import (
"fmt"
"io"
"os"
)
type Tree struct {
Children []*Tree
Value interface{}
}
func NewTree(v interface{}) *Tree {
return &Tree{
Children: []*Tree{},
Value: v,
}
}
func (t *Tree) String() string {
return fmt.Sprint(t.Value)
}
func (t *Tree) PrettyPrint(w io.Writer, prefix string) {
var inner func(int, *Tree)
inner = func(depth int, child *Tree) {
for i := 0; i < depth; i++ {
io.WriteString(w, prefix)
}
io.WriteString(w, child.String()+"\n") // you should really observe the return value here.
for _, grandchild := range child.Children {
inner(depth+1, grandchild)
}
}
inner(0, t)
}
func (t *Tree) AddChild(child interface{}) {
switch c := child.(type) {
case *Tree:
t.Children = append(t.Children, c)
default:
t.Children = append(t.Children, NewTree(c))
}
}
func main() {
root := NewTree("this is the root")
root.AddChild("this is a child")
root.AddChild("this is also a child")
root.AddChild("again, another child")
child := NewTree("now this one will have some children")
child.AddChild(5)
child.AddChild(1.3)
child.AddChild("the types can be mixed.")
grandchild := NewTree("etc, here's a grandhcild node.")
grandchild.AddChild("this one's a great grandchild")
grandchild.AddChild("semantic satiation means that the word child doesn't mean anything any more")
child.AddChild(grandchild)
child.AddChild("that's just fine. Maybe you don't want to do it, though")
root.AddChild(child)
root.AddChild("you see?")
root.AddChild("not so terrible.")
root.PrettyPrint(os.Stdout, "\t")
fmt.Print("\n\n\n\n")
child.PrettyPrint(os.Stdout, " - ")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment