Created
February 24, 2018 01:48
-
-
Save jackmott/6f17dfed4c16c705e50a43c1b06c4bb9 to your computer and use it in GitHub Desktop.
Expressions in Go
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
type Node interface { | |
Eval(x, y float32) float32 | |
String() string | |
SetParent(parent Node) | |
GetParent() Node | |
GetChildren() []Node | |
SetChildren([]Node) | |
AddRandom(node Node) | |
AddLeaf(leaf Node) bool | |
NodeCount() int | |
} | |
type BaseNode struct { | |
Parent Node | |
Children []Node | |
} | |
func (node *BaseNode) SetParent(parent Node) { | |
node.Parent = parent | |
} | |
//and so on so BaseNode satisfies the whole interface | |
//Then create a struct for each operation, or constant | |
type OpPlus struct { | |
BaseNode | |
} | |
//A constructor which forces the size of the children slice to be correct | |
func NewOpPlus() *OpPlus { | |
return &OpPlus{BaseNode{nil, make([]Node, 2)}} | |
} | |
// Then each operation must implement eval and string, the other interface | |
// functions are satisfied by the BaseNode embedded in the type | |
func (op *OpPlus) Eval(x, y float32) float32 { | |
return op.Children[0].Eval(x, y) + op.Children[1].Eval(x, y) | |
} | |
func (op *OpPlus) String() string { | |
return "( + " + op.Children[0].String() + " " + op.Children[1].String() + " )" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment