typestar

Generic map, filter and reduce in Go

What the standard library leaves to you, in ten lines.

func Map[T, U any](values []T, fn func(T) U) []U {
    out := make([]U, len(values))
    for i, value := range values {
        out[i] = fn(value)
    }
    return out
}

func Filter[T any](values []T, keep func(T) bool) []T {
    var out []T
    for _, value := range values {
        if keep(value) {
            out = append(out, value)
        }
    }
    return out
}

func Reduce[T, U any](values []T, start U, fn func(U, T) U) U {
    total := start
    for _, value := range values {
        total = fn(total, value)
    }
    return total
}

How it works

  1. Two type parameters let Map change the element type.
  2. The function argument does the work; the helper does the loop.
  3. Go has no method-chaining, so these compose by nesting.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
457
Tokens
165
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 90 seconds.

Type this snippet

Step 4 of 4 in Generics, step 16 of 19 in Interfaces & generics.

← Previous Next →