Skip to content

Instantly share code, notes, and snippets.

@patrickbucher
Created June 26, 2022 12:17
Show Gist options
  • Save patrickbucher/531d42af962bc1851a6132864705ea7d to your computer and use it in GitHub Desktop.
Save patrickbucher/531d42af962bc1851a6132864705ea7d to your computer and use it in GitHub Desktop.
package main
import "fmt"
type Numeric interface {
~int | ~float32 | ~float64
}
type Predicate[T any] func(T) bool
type Transform[T any] func(T) T
type Reduction[T any] func(T, T) T
func Filter[T any](items []T, p Predicate[T]) []T {
filtered := make([]T, 0)
for _, item := range items {
if p(item) {
filtered = append(filtered, item)
}
}
return filtered
}
func Map[T any](items []T, f Transform[T]) []T {
transformed := make([]T, 0)
for _, item := range items {
transformed = append(transformed, f(item))
}
return transformed
}
func Reduce[T any](items []T, start T, f Reduction[T]) T {
reduced := start
for _, item := range items {
reduced = f(item, reduced)
}
return reduced
}
func main() {
positive := func(x int) bool {
return x > 0
}
twice := func(x int) int {
return x * 2
}
sumUp := func(x, y int) int {
return x + y
}
numbers := []int{-3, 5, 2, -8, 9}
positives := Filter(numbers, positive)
doubled := Map(positives, twice)
summed := Reduce(doubled, 0, sumUp)
fmt.Println(summed)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment