Go

Generic Map / Filter / Reduce

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Three classic functional combinators, generically typed. Go's standard library doesn't ship these (yet), but they're short enough to drop into any project.
Go
Raw
package main

import "fmt"

func Map[T, U any](s []T, f func(T) U) []U {
    out := make([]U, len(s))
    for i, v := range s {
        out[i] = f(v)
    }
    return out
}

func Filter[T any](s []T, pred func(T) bool) []T {
    out := s[:0]                              // reuse backing array
    for _, v := range s {
        if pred(v) {
            out = append(out, v)
        }
    }
    return out
}

func Reduce[T, U any](s []T, init U, f func(U, T) U) U {
    acc := init
    for _, v := range s {
        acc = f(acc, v)
    }
    return acc
}

func main() {
    nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    squares := Map(nums, func(n int) int { return n * n })
    evens   := Filter(nums, func(n int) bool { return n%2 == 0 })
    sum     := Reduce(nums, 0, func(acc, n int) int { return acc + n })
    fmt.Println(squares, evens, sum)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.