Skip to content

Commit

Permalink
rename ReduceWithInitial to Fold
Browse files Browse the repository at this point in the history
  • Loading branch information
0x5a17ed committed May 27, 2024
1 parent dd4df87 commit 0d450b6
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
10 changes: 6 additions & 4 deletions itlib/each.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ func EachN[T any](it itkit.Iterator[T], fn EachNFn[T]) {

type AccumulatorFn[T, R any] func(R, T) R

// ReduceWithInitial reduces the given Iterator to a value which is the
// Fold reduces the given Iterator to a value which is the
// accumulated result of running each value through AccumulatorFn,
// where each successive invocation of AccumulatorFn is supplied
// the return value of the previous invocation.
func ReduceWithInitial[T, R any](initial R, it itkit.Iterator[T], fn AccumulatorFn[T, R]) (out R) {
func Fold[T, R any](initial R, it itkit.Iterator[T], fn AccumulatorFn[T, R]) (out R) {
out = initial
Apply(it, func(el T) { out = fn(out, it.Value()) })
return
Expand All @@ -97,14 +97,16 @@ func ReduceWithInitial[T, R any](initial R, it itkit.Iterator[T], fn Accumulator
// accumulated result of running each value through AccumulatorFn,
// where each successive invocation of AccumulatorFn is supplied
// the return value of the previous invocation.
//
// See [Fold] for a variant of this function that accepts an initial value.
func Reduce[T, R any](it itkit.Iterator[T], fn AccumulatorFn[T, R]) (out R) {
var zero R
return ReduceWithInitial(zero, it, fn)
return Fold(zero, it, fn)
}

// SumWithInitial accumulates the Iterator values based on the summation of their values.
func SumWithInitial[T constraints.Ordered](initial T, it itkit.Iterator[T]) T {
return ReduceWithInitial[T, T](initial, it, func(a, b T) T { return a + b })
return Fold[T, T](initial, it, func(a, b T) T { return a + b })
}

// Sum accumulates the Iterator values based on the summation of their values.
Expand Down
10 changes: 5 additions & 5 deletions itlib/each_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,13 @@ func TestEachIndex(t *testing.T) {
}

func TestReduce(t *testing.T) {
var n int
n := itlib.Reduce(sliceit.In([]int{1, 2, 3, 4, 5}), func(a, b int) int { return a*2 + b })
assertpkg.Equal(t, 57, n)
}

n = itlib.ReduceWithInitial(5, sliceit.In([]int{1, 2, 3, 4, 5}), func(a, b int) int { return a * b })
func TestFold(t *testing.T) {
n := itlib.Fold(5, sliceit.In([]int{1, 2, 3, 4, 5}), func(a, b int) int { return a * b })
assertpkg.Equal(t, 600, n)

n = itlib.Reduce(sliceit.In([]int{1, 2, 3, 4, 5}), func(a, b int) int { return a*2 + b })
assertpkg.Equal(t, 57, n)
}

func TestSum(t *testing.T) {
Expand Down

0 comments on commit 0d450b6

Please sign in to comment.