Skip to content

Instantly share code, notes, and snippets.

@islishude
Last active May 4, 2018 01:44
Show Gist options
  • Save islishude/22c7c57404c639a1c3301b2bafe4153e to your computer and use it in GitHub Desktop.
Save islishude/22c7c57404c639a1c3301b2bafe4153e to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"fmt"
)
// Rule struct
type Rule struct {
match func(x, y int) bool
action func(x, y int) int
}
func match(rules []Rule, x int, y int) (int, error) {
for _, t := range rules {
match := t.match
action := t.action
isMatch := match(x, y)
if isMatch {
return action(x, y), nil
}
}
return 0, errors.New("unmatched")
}
func main() {
rules := []Rule{
{
func(x, y int) bool {
if x < y {
return true
}
return false
},
func(x, y int) int { return y - x },
},
{
func(x, y int) bool {
if x > y {
return true
}
return false
},
func(x, y int) int { return y - x },
},
{
func(x, y int) bool {
if x == y {
return true
}
return false
},
func(x, y int) int { return y - x },
},
}
res, err := match(rules, 1, 2)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(res)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment