9. First class functions?
type Fi func() int
func doThing(s string, i int, fun Fi) {
fmt.Println(s) // ohai
fmt.Println(i) // 42
fmt.Println(fun) // pointer e.g. 0x2200
fmt.Println(fun()) // 1
}
func main() {
doThing("ohai", 42, func () int { return 1 })
}
11. Return other functions
type Fi func(int) int
func makeAdder(x int) Fi {
return func (y int) int {
return x + y
}
}
func main() {
add2 := makeAdder(2)
fmt.Println(add2(1)) // 3
fmt.Println(add2(2)) // 4
}
12. Take functions as arguments
type Fi func(int) int
type Fii func(int, int) int
func MakeFi(x int, fun Fii) Fi {
return func (y int) int {
return fun(x, y)
}
}
func main() {
even := MakeFi(2, func (x, y int) int { return x % y })
fmt.Println(even(1)) // 0
fmt.Println(even(4)) // 2
}
13. Pure Functions?
Idempotent, stateless and without side effect
// not pure
external := 1
func bad(i int) int {
external = i + external // side effect and state full
return external
}
fmt.Println(bad(external)) // 2
fmt.Println(bad(external)) // 4 not idempotent
// pure
external := 1
func good(x int) int {
// only uses variables in closure
// no side effects no state
return x + 1
}
fmt.Println(good(external)) // 2
fmt.Println(good(external)) // 2 idempotent