Debian Codegraph @

exp/higherorder/higherorder.go

raw
1 // Package higherorder provides higher-order functions for Go.
2 package higherorder
3
4 // Foldl applies a function to each element of a list, starting from the left.
5 // A single value is returned.
6 func Foldl[A any](f func(x, y A) A, start A, list []A) A {
7 for _, v := range list {
8 start = f(start, v)
9 }
10 return start
11 }
12
13 // Foldr applies a function to each element of a list, starting from the right.
14 // A single value is returned.
15 func Foldr[A any](f func(x, y A) A, start A, list []A) A {
16 for i := len(list) - 1; i >= 0; i-- {
17 start = f(start, list[i])
18 }
19 return start
20 }
21
22 // Map applies a given function to each element of a list, returning a new list.
23 func Map[A, B any](f func(A) B, list []A) []B {
24 res := make([]B, len(list))
25 for i, v := range list {
26 res[i] = f(v)
27 }
28 return res
29 }
30
31 // Filter applies a function to each element of a list, if the function returns false those elements are removed, returning a new list.
32 func Filter[A any](f func(A) bool, list []A) []A {
33 res := make([]A, 0)
34 for _, v := range list {
35 if f(v) {
36 res = append(res, v)
37 }
38 }
39 return res
40 }