Example of a High Order Function in Go:

package main
 
import "fmt"
 
func main() {
    numbers := []int{1, 2, 3, 4, 5}
 
    // use a higher-order function to declare what to do with each number
    doubledNumbers := mapInt(numbers, func(n int) int {
        return n * 2
    })
 
    // print the result
    fmt.Println(doubledNumbers)
}
 
// mapInt is a higher-order function that applies the given function to each element in the slice
func mapInt(nums []int, f func(int) int) []int {
    result := make([]int, len(nums))
    for i, n := range nums {
        result[i] = f(n)
    }
    return result
}

https://kyleshevlin.com/just-enough-fp-higher-order-functions/


🌱 Back to Garden