Skip to content

Instantly share code, notes, and snippets.

@cauefcr
Created April 28, 2021 02:40
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 cauefcr/31c9df46ddccc94f7a9e2ea60a1ff85c to your computer and use it in GitHub Desktop.
Save cauefcr/31c9df46ddccc94f7a9e2ea60a1ff85c to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
type CondTU []struct {
Comp func(string) bool
Ap func(string) int
}
func (c CondTU) Add(C func(string) bool, A func(string) int) CondTU {
c = append(c, struct {
Comp func(string) bool
Ap func(string) int
}{
Comp: C,
Ap: A,
})
return c
}
func (c CondTU) Call(inp string) int {
for _, v := range c {
if v.Comp(inp) {
return v.Ap(inp)
}
}
return 0
}
func cond(Comp []func(...string) bool, Ap []func(...string) int) func(...string) int {
if len(Comp) != len(Ap) {
panic("comp must be the same length as ap")
}
return func(inp ...string) int {
for i, C := range Comp {
if C(inp...) {
return Ap[i](inp...)
}
}
return 0
}
}
type condTest func(string) int
func (c condTest) Add(C func(string) bool, A func(string) int) condTest {
return func(inp string) int {
if C(inp) {
return A(inp)
}
return c(inp)
}
}
func main() {
strtoi := cond([]func(...string) bool{
func(inp ...string) bool {
return inp[0] == "0"
},
func(inp ...string) bool {
return inp[0] == "1"
},
}, []func(...string) int{
func(inp ...string) int {
return 0
},
func(s ...string) int {
return 1
},
})
strtoi2 := CondTU{}.Add(func(t string) bool {
return t == string("0")
}, func(t string) int {
return int(0)
}).Add(func(t string) bool { return t == "1" }, func(t string) int { return 1 })
strtoi3 := condTest(func(t string) int {
return 0
}).Add(func(t string) bool {
return t == "1"
}, func(t string) int {
return 1
})
fmt.Printf("%+V x %+V x %+V\n", strtoi("0"), strtoi2.Call("0"), strtoi3("0"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment