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