underscore/docs/content/collections/foldright.md
Ruidy bcb4dd1e9d
docs: add documentation for new collection functions
Add comprehensive documentation for all new functions:
- TakeWhile: take elements while predicate is true
- DropWhile: drop elements while predicate is true
- Scan: running accumulator (prefix scan)
- First/FirstN: get first element(s) safely
- Init: all but last element
- Intersperse: insert separator between elements
- Sliding: sliding window views
- FoldRight: right-to-left fold/reduce
- Tap: side effects without mutation
- Transpose: flip matrix rows/columns
- Unzip: split tuples into separate slices
- ParallelReduce: parallel reduction (experimental)
- Replicate: create n copies of a value

Each doc includes:
- Clear description
- Code examples with output
- Common use cases
- Edge case handling

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-16 08:48:38 +01:00

1 KiB

title date
FoldRight 2025-01-16T00:00:00-00:00

FoldRight is like Reduce but processes elements from right to left. Also known as foldr in Haskell. Important for non-associative operations where the order of evaluation matters.

package main

import (
	"fmt"
	u "github.com/rjNemo/underscore"
)

func main() {
	// Subtraction is non-associative
	nums := []int{1, 2, 3}

	// FoldRight: 1 - (2 - (3 - 0)) = 1 - (2 - 3) = 1 - (-1) = 2
	result := u.FoldRight(nums, 0, func(n, acc int) int { return n - acc })
	fmt.Println(result) // 2

	// Compare with Reduce (left fold): (0 - 1) - 2 - 3 = -6
	leftResult := u.Reduce(nums, func(n, acc int) int { return acc - n }, 0)
	fmt.Println(leftResult) // -6

	// Building a list in order
	buildList := u.FoldRight(nums, []int{}, func(n int, acc []int) []int {
		return append([]int{n}, acc...)
	})
	fmt.Println(buildList) // [1, 2, 3]

	// String concatenation
	words := []string{"a", "b", "c"}
	concat := u.FoldRight(words, "", func(s, acc string) string { return s + acc })
	fmt.Println(concat) // "abc"
}