lambda/fold.go

29 lines
439 B
Go
Raw Normal View History

2022-03-26 19:16:31 +00:00
package lambda
2022-03-26 22:22:54 +00:00
func Foldr[T any](xs []T, fx func(T, T) T) T {
2022-03-26 19:21:17 +00:00
if len(xs) < 1 {
return *new(T)
}
2022-03-26 22:01:10 +00:00
if len(xs) == 1 {
return xs[0]
}
2022-03-26 19:21:17 +00:00
for i := 1; i < len(xs); i++ {
xs[0] = fx(xs[0], xs[i])
}
return xs[0]
2022-03-26 19:16:31 +00:00
}
2022-03-26 22:22:54 +00:00
func Foldl[T any](xs []T, fx func(T, T) T) T {
2022-03-26 19:21:17 +00:00
if len(xs) < 1 {
return *new(T)
}
2022-03-26 22:01:10 +00:00
if len(xs) == 1 {
return xs[0]
}
2022-03-26 19:21:17 +00:00
li := len(xs) - 1
for i := li - 1; i >= 0; i-- {
xs[li] = fx(xs[li], xs[i])
}
return xs[li]
2022-03-26 19:16:31 +00:00
}