Taskintro
Reduce a list to a value
Also called fold a list, aggregate a list, sum a list, accumulate, inject, catamorphism, sum of an array.
Combine the items of a list into one value with an accumulator, here the sum of a list of integers, and give an initial value for the empty list.
- Evidence
- Code in 10 languages
Task
Reduce a list of integers to one value, the sum of the items. The function total(items) starts with an accumulator of 0. For each item, it adds the item to the accumulator. For example, total([1, 2, 3, 4]) is 10, and total([]) is 0.
A reduce is also known as a fold or an aggregate. It takes a list, an initial value and a function of two arguments. The function takes the accumulator and the next item, and returns the next accumulator. The initial value is also the result for an empty list.
The items are 32-bit signed integers, and the total fits in a 32-bit signed integer. A partial sum can be outside this range. For example, the total of [2147483647, 1, -1] is 2147483647, but the partial sum after the second item is 2147483648.
Solutions
| Language | Reduce the integers to their sum |
|---|---|
| Python | reduce(add, items, 0) |
| JavaScript, TypeScript | items.reduce((acc, x) => acc + x, 0) |
| Java | Arrays.stream(items).asLongStream().reduce(0L, Long::sum) |
| C# | items.Aggregate(0L, (acc, x) => acc + x) |
| Go | a for loop with an int64 accumulator |
| Rust | items.iter().fold(0i64, |acc, &x| acc + i64::from(x)) |
| C | a for loop with a long long accumulator |
| C++ | std::accumulate(items.begin(), items.end(), 0LL) |
| Bash | a for loop with acc=$((acc + x)) |
- Python. The third argument of
reduceis the initial value. "If the optional initial is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty"1. - Java.
IntStream.sumis a reduce too: "This is a special case of a reduction"2. The solution adds the items aslongvalues, thenMath.toIntExactmakes theintresult. - C#. The seed
0Lsets the type of the accumulator tolong.checkedmakes the conversion tointfail if the total does not fit. - Go. The standard library has no reduce function, so the solution uses a loop. The accumulator is an
int64, because anintis "either 32 or 64 bits"3. - Rust.
fold"Folds every element into an accumulator by applying an operation, returning the final result"4.i32::try_frommakes the result. - C. C has no reduce function, so the solution uses a loop. A
long longaccumulator holds each partial sum. - C++. "std::accumulate performs a left fold"5. The initial value
0LLsets the type of the accumulator. - Bash. Bash has no reduce function, so the solution uses a loop over the arguments.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: the sum of an empty list is 0, the initial value.single: the sum of one item is that item.negativeandzero-sum: negative items make the sum smaller, and[5, -5]gives 0.max,minandto-the-limit: the total can be -2147483648 or 2147483647.partial-overflowandpartial-underflow: a partial sum is outside the 32-bit range, but the total is in it. A 32-bit accumulator overflows for these cases.
Pitfalls
- Python reduce of an empty list needs an initial value. "If initial is not given and iterable contains only one item, the first item is returned"1. For an empty list without an initial value,
reduceraises aTypeError:
from functools import reduce
from operator import add
print(reduce(add, [1, 2, 3], 0))
print(reduce(add, [], 0))
try:
reduce(add, [])
except TypeError as e:
print(type(e).__name__)
6
0
TypeError
- JavaScript reduce of an empty array needs an initial value.
reducethrows aTypeError"if the array contains no elements and initialValue is not provided"6:
console.log([1, 2, 3].reduce((acc, x) => acc + x, 0));
console.log([].reduce((acc, x) => acc + x, 0));
try {
[].reduce((acc, x) => acc + x);
} catch (e) {
console.log(e.name);
}
6
0
TypeError
- Java int sums overflow with no exception. In the example, the
intsum ofInteger.MAX_VALUEand 1 isInteger.MIN_VALUE. Add the items aslongvalues:
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int[] big = {Integer.MAX_VALUE, 1};
// The int sum overflows with no exception.
System.out.println(IntStream.of(big).sum());
// A long sum holds the result.
System.out.println(IntStream.of(big).asLongStream().sum());
}
}
-2147483648
2147483648
- C# Aggregate without a seed fails for an empty sequence. It throws an
InvalidOperationExceptionwhen the "source contains no elements"7. Give a seed:
using System;
using System.Linq;
int[] empty = [];
Console.WriteLine(empty.Aggregate(0, (acc, x) => acc + x));
try
{
Console.WriteLine(empty.Aggregate((acc, x) => acc + x));
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.GetType().Name);
}
0
InvalidOperationException
- Go integer accumulators wrap around. "For signed integers, the operations +, -, *, /, and << may legally overflow"3. In the example, the
int32accumulator wraps to -2147483648, and theint64accumulator holds 2147483648:
package main
import "fmt"
func main() {
items := []int32{2147483647, 1}
var small int32
var big int64
for _, x := range items {
small += x
big += int64(x)
}
fmt.Println(small, big)
}
-2147483648 2147483648
- Rust sum can panic. For
sum, "this method will panic if the computation overflows and overflow checks are enabled"4. A release build has no overflow checks by default. Usetry_foldwithchecked_addto getNone, or a wider accumulator:
fn main() {
let items: [i32; 2] = [i32::MAX, 1];
let checked = items.iter().try_fold(0i32, |acc, &x| acc.checked_add(x));
println!("{checked:?}");
let wide = items.iter().fold(0i64, |acc, &x| acc + i64::from(x));
println!("{wide}");
}
None
2147483648
- C signed overflow is undefined. "When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined"8. Thus a test cannot show the overflow of an
intsum. The example adds the items to along long, and the partial sum 2147483648 is correct:
#include <limits.h>
#include <stdio.h>
int main(void) {
int items[] = {INT_MAX, 1, -1};
long long acc = 0;
for (size_t i = 0; i < sizeof items / sizeof items[0]; i++) {
acc += items[i];
printf("%lld\n", acc);
}
return 0;
}
2147483647
2147483648
2147483647
- C++ accumulate uses the type of the initial value. "std::accumulate(v.begin(), v.end(), 0) likely does not give the result one wishes for when v is of type std::vector"5. In the example, the initial value
0makes each partial sum anint, so the result is 0. The initial value0.0gives 1.5:
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<double> v{0.5, 0.5, 0.5};
std::cout << std::accumulate(v.begin(), v.end(), 0) << '\n';
std::cout << std::accumulate(v.begin(), v.end(), 0.0) << '\n';
}
0
1.5
- Bash arithmetic wraps around. "Evaluation is done in the largest fixed-width integers available, with no check for overflow"9. In the example, the largest 64-bit value plus 1 gives the smallest 64-bit value:
total() {
local acc=0 x
for x in "$@"; do
acc=$((acc + x))
done
printf '%s\n' "$acc"
}
total 1 2 3
total
echo $((9223372036854775807 + 1))
6
0
-9223372036854775808
Related tasks
- Map over a list: make a new list from each item.
- Filter a list: keep the items that pass a test.
- Find the largest element: a reduce that keeps the larger of two values.
- Count the items of each kind: a reduce to a map of counts.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
from functools import reduce
from operator import add
def total(items: list[int]) -> int:
"""Return the sum of items. The sum of an empty list is 0."""
# The initial value 0 is the result for an empty list.
return reduce(add, items, 0)
test_total.py 26 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
import pytest
from total import total
CASES = {
"small": ([1, 2, 3, 4], 10),
"mixed": ([10, -3, 5], 12),
"empty": ([], 0),
"single": ([7], 7),
"negative": ([-1, -2, -3], -6),
"zero-sum": ([5, -5], 0),
"max": ([2147483647], 2147483647),
"min": ([-2147483648], -2147483648),
"to-the-limit": ([2147483646, 1], 2147483647),
"partial-overflow": ([2147483647, 1, -1], 2147483647),
"partial-underflow": ([-2147483648, -1, 1], -2147483648),
}
@pytest.mark.parametrize("name", CASES)
def test_total(name):
items, want = CASES[name]
assert total(items) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
#include "total.hpp"
#include <numeric>
#include <span>
int total(std::span<const int> items) {
// The type of the initial value is the type of the accumulator, so 0LL
// gives a long long.
return static_cast<int>(std::accumulate(items.begin(), items.end(), 0LL));
}
total.hpp 9 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
#pragma once
#include <span>
// total returns the sum of the items. The sum of no items is 0.
int total(std::span<const int> items);
test_total.cpp 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
#include "total.hpp"
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<int> &items, int want) {
if (total(items) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("small", std::vector<int>{1, 2, 3, 4}, 10);
check("mixed", std::vector<int>{10, -3, 5}, 12);
check("empty", std::vector<int>{}, 0);
check("single", std::vector<int>{7}, 7);
check("negative", std::vector<int>{-1, -2, -3}, -6);
check("zero-sum", std::vector<int>{5, -5}, 0);
check("max", std::vector<int>{2147483647}, 2147483647);
check("min", std::vector<int>{(-2147483647 - 1)}, (-2147483647 - 1));
check("to-the-limit", std::vector<int>{2147483646, 1}, 2147483647);
check("partial-overflow", std::vector<int>{2147483647, 1, -1}, 2147483647);
check("partial-underflow", std::vector<int>{(-2147483647 - 1), -1, 1}, (-2147483647 - 1));
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
import java.util.Arrays;
final class Total {
private Total() {}
/** Returns the sum of items. The sum is in a long, so a partial sum does not overflow. */
static int total(int[] items) {
long sum = Arrays.stream(items).asLongStream().reduce(0L, Long::sum);
return Math.toIntExact(sum);
}
}
TotalTest.java 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class TotalTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("small", new int[] {1, 2, 3, 4}, 10),
Arguments.of("mixed", new int[] {10, -3, 5}, 12),
Arguments.of("empty", new int[] {}, 0),
Arguments.of("single", new int[] {7}, 7),
Arguments.of("negative", new int[] {-1, -2, -3}, -6),
Arguments.of("zero-sum", new int[] {5, -5}, 0),
Arguments.of("max", new int[] {2147483647}, 2147483647),
Arguments.of("min", new int[] {-2147483648}, -2147483648),
Arguments.of("to-the-limit", new int[] {2147483646, 1}, 2147483647),
Arguments.of("partial-overflow", new int[] {2147483647, 1, -1}, 2147483647),
Arguments.of("partial-underflow", new int[] {-2147483648, -1, 1}, -2147483648));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void total(String name, int[] items, int want) {
assertEquals(want, Total.total(items));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
#include "total.h"
int total(const int *items, size_t n) {
// A long long holds each partial sum, so no int addition overflows.
long long acc = 0;
for (size_t i = 0; i < n; i++) {
acc += items[i];
}
return (int)acc;
}
total.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
#ifndef TOTAL_H
#define TOTAL_H
#include <stddef.h>
// total returns the sum of items[0..n). The sum of no items is 0.
int total(const int *items, size_t n);
#endif
test_total.c 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
#include "total.h"
#include <stdbool.h>
#include <stdio.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
#define CHECK(name, n, given, want) \
do { \
const int g[] = given; \
int got = total(g, n); \
if (got != (want)) { \
fprintf(stderr, "case %s: got %d, want %d\n", name, got, want); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("small", 4, L(1, 2, 3, 4), 10);
CHECK("mixed", 3, L(10, -3, 5), 12);
CHECK("empty", 0, L(0), 0);
CHECK("single", 1, L(7), 7);
CHECK("negative", 3, L(-1, -2, -3), -6);
CHECK("zero-sum", 2, L(5, -5), 0);
CHECK("max", 1, L(2147483647), 2147483647);
CHECK("min", 1, L((-2147483647 - 1)), (-2147483647 - 1));
CHECK("to-the-limit", 2, L(2147483646, 1), 2147483647);
CHECK("partial-overflow", 3, L(2147483647, 1, -1), 2147483647);
CHECK("partial-underflow", 3, L((-2147483647 - 1), -1, 1), (-2147483647 - 1));
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
using System.Linq;
public static class Total
{
// The seed 0L gives a long accumulator, and the result for an empty array.
public static int Of(int[] items) => checked((int)items.Aggregate(0L, (acc, x) => acc + x));
}
TotalTests.cs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
using Xunit;
public sealed class TotalTests
{
public static TheoryData<string, int[], int> Cases => new()
{
{ "small", new int[] { 1, 2, 3, 4 }, 10 },
{ "mixed", new int[] { 10, -3, 5 }, 12 },
{ "empty", new int[0], 0 },
{ "single", new int[] { 7 }, 7 },
{ "negative", new int[] { -1, -2, -3 }, -6 },
{ "zero-sum", new int[] { 5, -5 }, 0 },
{ "max", new int[] { 2147483647 }, 2147483647 },
{ "min", new int[] { -2147483648 }, -2147483648 },
{ "to-the-limit", new int[] { 2147483646, 1 }, 2147483647 },
{ "partial-overflow", new int[] { 2147483647, 1, -1 }, 2147483647 },
{ "partial-underflow", new int[] { -2147483648, -1, 1 }, -2147483648 },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[] items, int want)
{
Assert.NotNull(name);
Assert.Equal(want, Total.Of(items));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
/**
* @param {number[]} items
* @returns {number}
*/
export function total(items) {
// The initial value 0 is the result for an empty array. Without it,
// reduce throws a TypeError for an empty array.
return items.reduce((acc, x) => acc + x, 0);
}
total.test.js 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { total } from "./total.js";
const cases = [
["small", [1, 2, 3, 4], 10],
["mixed", [10, -3, 5], 12],
["empty", [], 0],
["single", [7], 7],
["negative", [-1, -2, -3], -6],
["zero-sum", [5, -5], 0],
["max", [2147483647], 2147483647],
["min", [-2147483648], -2147483648],
["to-the-limit", [2147483646, 1], 2147483647],
["partial-overflow", [2147483647, 1, -1], 2147483647],
["partial-underflow", [-2147483648, -1, 1], -2147483648],
];
for (const [name, items, want] of cases) {
test(name, () => {
assert.deepEqual(total(items), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
export function total(items: readonly number[]): number {
// The initial value 0 is the result for an empty array. Without it,
// reduce throws a TypeError for an empty array.
return items.reduce((acc, x) => acc + x, 0);
}
total.test.ts 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { total } from "./total.ts";
const cases: [string, number[], number][] = [
["small", [1, 2, 3, 4], 10],
["mixed", [10, -3, 5], 12],
["empty", [], 0],
["single", [7], 7],
["negative", [-1, -2, -3], -6],
["zero-sum", [5, -5], 0],
["max", [2147483647], 2147483647],
["min", [-2147483648], -2147483648],
["to-the-limit", [2147483646, 1], 2147483647],
["partial-overflow", [2147483647, 1, -1], 2147483647],
["partial-underflow", [-2147483648, -1, 1], -2147483648],
];
for (const [name, items, want] of cases) {
test(name, () => {
assert.deepEqual(total(items), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
// Package total adds the items of a slice.
package total
// Total returns the sum of items. The sum of an empty slice is 0.
func Total(items []int) int {
// The accumulator is an int64, because an int can have 32 bits.
var acc int64
for _, x := range items {
acc += int64(x)
}
return int(acc)
}
total_test.go 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
package total
import "testing"
var cases = []struct {
name string
items []int
want int
}{
{"small", []int{1, 2, 3, 4}, 10},
{"mixed", []int{10, -3, 5}, 12},
{"empty", []int{}, 0},
{"single", []int{7}, 7},
{"negative", []int{-1, -2, -3}, -6},
{"zero-sum", []int{5, -5}, 0},
{"max", []int{2147483647}, 2147483647},
{"min", []int{-2147483648}, -2147483648},
{"to-the-limit", []int{2147483646, 1}, 2147483647},
{"partial-overflow", []int{2147483647, 1, -1}, 2147483647},
{"partial-underflow", []int{-2147483648, -1, 1}, -2147483648},
}
func TestTotal(t *testing.T) {
for _, c := range cases {
if got := Total(c.items); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
/// Returns the sum of `items`. The sum of an empty slice is 0.
pub fn total(items: &[i32]) -> i32 {
// The i64 accumulator holds each partial sum of i32 items.
let sum = items.iter().fold(0i64, |acc, &x| acc + i64::from(x));
i32::try_from(sum).expect("total: the sum does not fit in an i32")
}
tests/total_test.rs 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
use algo_reduce_a_list_to_a_value::total;
#[test]
fn cases() {
let cases: &[(&str, &[i32], i32)] = &[
("small", &[1, 2, 3, 4], 10),
("mixed", &[10, -3, 5], 12),
("empty", &[], 0),
("single", &[7], 7),
("negative", &[-1, -2, -3], -6),
("zero-sum", &[5, -5], 0),
("max", &[2147483647], 2147483647),
("min", &[-2147483648], -2147483648),
("to-the-limit", &[2147483646, 1], 2147483647),
("partial-overflow", &[2147483647, 1, -1], 2147483647),
("partial-underflow", &[-2147483648, -1, 1], -2147483648),
];
for &(name, items, want) in cases {
assert_eq!(total(items), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
# total ITEM...
# Prints the sum of the integer arguments. The sum of no arguments is 0.
total() {
local acc=0 x
for x in "$@"; do
acc=$((acc + x))
done
printf '%s\n' "$acc"
}
test_total.bats 37 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/reduce-a-list-to-a-value/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/total.sh"
}
lines() { # lines ITEM...: prints each item on a line, and nothing for no items
if (($# > 0)); then printf '%s\n' "$@"; fi
}
check() { # check FUNCTION GIVEN... -- WANT...
local fn=$1 got want
shift
local -a given=()
while [ "$1" != -- ]; do given+=("$1"); shift; done
shift
# The x keeps the trailing newlines, which $(...) removes.
got=$("$fn" "${given[@]}"; printf x)
want=$(lines "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "small" { check total 1 2 3 4 -- 10; }
@test "mixed" { check total 10 -3 5 -- 12; }
@test "empty" { check total -- 0; }
@test "single" { check total 7 -- 7; }
@test "negative" { check total -1 -2 -3 -- -6; }
@test "zero-sum" { check total 5 -5 -- 0; }
@test "max" { check total 2147483647 -- 2147483647; }
@test "min" { check total -2147483648 -- -2147483648; }
@test "to-the-limit" { check total 2147483646 1 -- 2147483647; }
@test "partial-overflow" { check total 2147483647 1 -1 -- 2147483647; }
@test "partial-underflow" { check total -2147483648 -1 1 -- -2147483648; }
References
- The Python Standard Library, functools, functools.reduce()
- Java SE 25 API, Interface IntStream, sum()
- The Go Programming Language Specification, Integer overflow, Numeric types
- Rust standard library, trait Iterator, fold, sum
- cppreference.com, std::accumulate, Notes
- MDN Web Docs, Array.prototype.reduce(), Exceptions
- .NET API reference, Enumerable.Aggregate method, Exceptions
- cppreference.com, Arithmetic operators (C), Overflows
- Bash Reference Manual, 6.5 Shell Arithmetic
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag WS8915 Edit this page History Report an error Markdown