Last active
August 22, 2020 09:48
-
-
Save ztk37/041f6e857bd2b4de7e44b88633d0b70c to your computer and use it in GitHub Desktop.
Golang Tree Composite
This file contains hidden or 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 ( | |
| "fmt" | |
| "strings" | |
| ) | |
| type NodeType int | |
| const ( | |
| NodeEmpty NodeType = iota | |
| NodeLeaf | |
| NodeBranch | |
| ) | |
| type Node interface { | |
| Type() NodeType | |
| String() string | |
| } | |
| type EmptyNode struct{} | |
| func Empty() Node { | |
| return EmptyNode{} | |
| } | |
| func (e EmptyNode) Type() NodeType { | |
| return NodeEmpty | |
| } | |
| func (e EmptyNode) String() string { | |
| return "\n" | |
| } | |
| type LeafNode struct { | |
| Text string `json:"text"` | |
| } | |
| func Leaf(text string) Node { | |
| return LeafNode{text} | |
| } | |
| func (l LeafNode) String() string { | |
| return l.Text | |
| } | |
| func (l LeafNode) Type() NodeType { | |
| return NodeLeaf | |
| } | |
| type BranchNode struct { | |
| Nodes []Node `json:"nodes"` | |
| } | |
| func Branch(nodes ...Node) Node { | |
| return BranchNode{nodes} | |
| } | |
| func (b BranchNode) String() string { | |
| var out strings.Builder | |
| for _, node := range l.Nodes { | |
| out.WriteString(node.String()) | |
| } | |
| return out.String() | |
| } | |
| func (b BranchNode) Type() NodeType { | |
| return NodeBranch | |
| } | |
| func main() { | |
| tree := Branch( | |
| Leaf("Foo\n"), | |
| Empty(), | |
| Leaf("Fib\n"), | |
| Branch( | |
| Leaf("Foo\n"), | |
| Branch( | |
| Leaf("Foo\n"), | |
| Leaf("Bar\n"), | |
| Empty(), | |
| ), | |
| Leaf("Fib\n"), | |
| ), | |
| ) | |
| fmt.Println(tree) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment