Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
go higher order functions
package main
import "fmt"
func collect(vals []int, f func(int) int) []int {
length := len(vals)
newVals := make([]int, length, length)
for i, val := range vals {
newVals[i] = f(val)
}
return newVals
}
func main() {
ints := []int{1, 2, 3, 4, 5}
result := collect(ints, func (a int) int {
return a + 1
})
fmt.Println(result)
}
package main
import "fmt"
func comb(a, b func(int) int) func(int) int {
return func(x int) int {
return a(b(x))
}
}
func main() {
add1 := func(x int) int {
return x + 1
}
add2 := func(x int) int {
return x + 2
}
add3 := comb(add1, add2)
fmt.Println(add3(4))
}
package main
import "fmt"
func partial(f func(int, int) int, a int) func(int) int {
return func(x int) int {
return f(a, x)
}
}
func main() {
add := func(a, b int) int {
return a + b
}
add4 := partial(add, 4)
fmt.Println(add4(2))
}
package main
import "fmt"
func reduce(vals []int, init int, f func(int, int) int) int {
result := init
for _, val := range vals {
result = f(result, val)
}
return result
}
func main() {
ints := []int{1, 2, 3, 4, 5}
result := reduce(ints, 0, func (sum, i int) int {
return sum + i
})
fmt.Println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment