Last active
March 15, 2022 19:27
-
-
Save patrickbucher/600370a6132474b90912c04f5217f125 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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