Skip to content

Instantly share code, notes, and snippets.

@jackmott
Created February 24, 2018 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackmott/6f17dfed4c16c705e50a43c1b06c4bb9 to your computer and use it in GitHub Desktop.
Save jackmott/6f17dfed4c16c705e50a43c1b06c4bb9 to your computer and use it in GitHub Desktop.
Expressions in Go
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