Last active
December 6, 2020 19:34
-
-
Save ksurent/83e83cec5ae0e6b5ed4bae6434e36e24 to your computer and use it in GitHub Desktop.
Silly Go–with–generics (FGG) program to demonstrate the syntax.
This file contains hidden or 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" | |
func Fold(type T, U)(acc T, f func(T, U) T, xs []U) T { | |
for _, x := range xs { | |
acc = f(acc, x) | |
} | |
return acc | |
} | |
func Map(type T, U)(xs []T, f func(T) U) []U { | |
ys := make([]U, 0, len(xs)) | |
ys = Fold(ys, func(acc []U, x T) []U { return append(acc, f(x)) }, xs) | |
return ys | |
} | |
func Filter(type T)(xs []T, f func(T) bool) []T { | |
ys := make([]T, 0, len(xs)) | |
ys = Fold( | |
ys, | |
func(acc []T, x T) []T { if f(x) { return append(acc, x) } else { return acc } }, | |
xs, | |
) | |
if len(ys) != len(xs) { | |
ys = ys[:len(ys):len(ys)] | |
} | |
return ys | |
} | |
func main() { | |
incremented := Map([]int{1,2,3}, func(x int) int { return x + 1}) | |
filtered := Filter(incremented, func(x int) bool { return x % 2 == 0 }) | |
summed := Fold(0, func(acc int, x int) int { return acc + x }, filtered) | |
fmt.Println(incremented, filtered, summed) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment