mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
- Add FoldRight: fold/reduce from right to left - Useful for non-associative operations - Comprehensive tests including comparison with Reduce - Benchmark included Example: FoldRight([1,2,3], 0, subtract) → 1-(2-(3-0)) = 2 Resolves Issue 20 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <noreply@anthropic.com>
13 lines
415 B
Go
13 lines
415 B
Go
package underscore
|
|
|
|
// FoldRight is like Reduce but processes elements from right to left.
|
|
// Also known as foldr in Haskell.
|
|
//
|
|
// Example: FoldRight([]int{1,2,3}, 0, func(n, acc int) int { return n - acc })
|
|
// → 1 - (2 - (3 - 0)) = 1 - (2 - 3) = 1 - (-1) = 2
|
|
func FoldRight[T, P any](values []T, acc P, fn func(T, P) P) P {
|
|
for i := len(values) - 1; i >= 0; i-- {
|
|
acc = fn(values[i], acc)
|
|
}
|
|
return acc
|
|
}
|