(fun)ctional go
First class/Pure functions
Higher Order Functions
Immutability(kinda)
Currying
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 })}
Higher order functions?
Return other functionstype 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}
Take functions as argumentstype Fi func(int) inttype 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}
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)) // 2fmt.Println(bad(external)) // 4 not idempotent
// pureexternal := 1
func good(x int) int { // only uses variables in closure // no side effects no state return x + 1}
fmt.Println(good(external)) // 2fmt.Println(good(external)) // 2 idempotent
Immutability
An immutable object is an object whose state cannot be modified after it is created.
Currying Is the technique of transforming a function that takes multiple arguments in such a way that it
can be called as a chain.
func makeAdd(a int) func(int) int { return func(b int) int { return a + b }}
func main() { add2 := makeAdd(2) add3 := makeAdd(3) fmt.Println(add2(5), add3(6))}
func modulo(x, y int) int { return x % y}
func makeModulo(x int) func(int) int { return func(y int) int { return modulo(x, y) }}
func main() { isOdd := makeModulo(2) fmt.Println(isOdd(2)) // 0 fmt.Println(isOdd(3)) // 2}
How about something useful?
Thank you!Chirstan Johansen, Brian Lonsdorf and Everyone at
UBXD
Top Related