Skip to content

Commit 7644fd6

Browse files
committed
Add Enum.sum/2
1 parent 134941e commit 7644fd6

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

lib/elixir/lib/enum.ex

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3473,6 +3473,29 @@ defmodule Enum do
34733473
reduce(enumerable, 0, &+/2)
34743474
end
34753475

3476+
@doc """
3477+
Maps and sums the given enumerable in one pass.
3478+
3479+
Raises `ArithmeticError` if `fun` returns a non-numeric value.
3480+
3481+
## Examples
3482+
3483+
iex> Enum.sum([%{count: 1}, %{count: 2}, %{count: 3}], fn x -> x.count end)
3484+
6
3485+
3486+
iex> Enum.sum(1..3, fn x -> x ** 2 end)
3487+
14
3488+
3489+
iex> Enum.sum([], fn x -> x.count end)
3490+
0
3491+
3492+
"""
3493+
@doc since: "1.16.0"
3494+
@spec sum(t, (element -> number)) :: number
3495+
def sum(enumerable, fun) when is_function(fun, 1) do
3496+
reduce(enumerable, 0, fn x, acc -> acc + fun.(x) end)
3497+
end
3498+
34763499
@doc """
34773500
Returns the product of all elements.
34783501

lib/elixir/test/elixir/enum_test.exs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1321,6 +1321,24 @@ defmodule EnumTest do
13211321
end
13221322
end
13231323

1324+
test "sum/2" do
1325+
assert Enum.sum([], &hd/1) == 0
1326+
assert Enum.sum([[1]], &hd/1) == 1
1327+
assert Enum.sum([[1], [2], [3]], &hd/1) == 6
1328+
assert Enum.sum([[1.1], [2.2], [3.3]], &hd/1) == 6.6
1329+
assert Enum.sum([[-3], [-2], [-1], [0], [1], [2], [3]], &hd/1) == 0
1330+
1331+
assert Enum.sum(1..3, &(&1 ** 2)) == 14
1332+
1333+
assert_raise ArithmeticError, fn ->
1334+
Enum.sum([[{}]], &hd/1)
1335+
end
1336+
1337+
assert_raise ArithmeticError, fn ->
1338+
Enum.sum([[1], [{}]], &hd/1)
1339+
end
1340+
end
1341+
13241342
test "product/1" do
13251343
assert Enum.product([]) == 1
13261344
assert Enum.product([1]) == 1

0 commit comments

Comments
 (0)