Last active
May 4, 2018 01:44
-
-
Save islishude/22c7c57404c639a1c3301b2bafe4153e to your computer and use it in GitHub Desktop.
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
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