Reduce function for arrays/slices in Go

How to write a functional Reduce function in Go using generics, including a unit test. The foundation for many functional programming libraries!


Reduce applies a binary function to each element in the input slice and an accumulator, returning the final value of the accumulator. The function f takes an accumulator of type B and an element of type A and returns a new accumulator of type B.

func Reduce[A any, B any](input []A, initial B, f func(B, A) B) B {
	accumulator := initial
	for _, v := range input {
		accumulator = f(accumulator, v)
	}
	return accumulator
}

and this is a unittest for the function:

func TestReduce(t *testing.T) {
	input := []int{1, 2, 3, 4, 5}
	initial := 0
	f := func(b int, a int) int {
		return b + a
	}
	expected := 15
	result := util.Reduce(input, initial, f)
	if expected != result {
		t.Errorf("Expected %v, got %v", expected, result)
	}
}

Linked Technologies

What it's made of

illustration of Go
Go

Fast, simple, and efficient. Ideal for solopreneurs, Go's straightforward syntax and powerful performance allow for quick development and deployment.

Linked Categories

Where it's useful

illustration of Data Engineering
Data Engineering

Explore the essentials of Data Engineering, delving into how data systems are built and maintained. From organizing data flows to automating complex data processes, discover the tools and techniques that make data easily accessible and useful for everyday projects and insights.