Skip to content

Commit f720ff5

Browse files
committed
Add Enum.sum/2
1 parent a406527 commit f720ff5

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
@@ -3449,6 +3449,29 @@ defmodule Enum do
34493449
reduce(enumerable, 0, &+/2)
34503450
end
34513451

3452+
@doc """
3453+
Maps and sums the given enumerable in one pass.
3454+
3455+
Raises `ArithmeticError` if `fun` returns a non-numeric value.
3456+
3457+
## Examples
3458+
3459+
iex> Enum.sum([%{count: 1}, %{count: 2}, %{count: 3}], fn x -> x.count end)
3460+
6
3461+
3462+
iex> Enum.sum(1..3, fn x -> x ** 2 end)
3463+
14
3464+
3465+
iex> Enum.sum([], fn x -> x.count end)
3466+
0
3467+
3468+
"""
3469+
@doc since: "1.16.0"
3470+
@spec sum(t, (element -> number)) :: number
3471+
def sum(enumerable, fun) when is_function(fun, 1) do
3472+
reduce(enumerable, 0, fn x, acc -> acc + fun.(x) end)
3473+
end
3474+
34523475
@doc """
34533476
Returns the product of all elements.
34543477

lib/elixir/test/elixir/enum_test.exs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1307,6 +1307,24 @@ defmodule EnumTest do
13071307
end
13081308
end
13091309

1310+
test "sum/2" do
1311+
assert Enum.sum([], &hd/1) == 0
1312+
assert Enum.sum([[1]], &hd/1) == 1
1313+
assert Enum.sum([[1], [2], [3]], &hd/1) == 6
1314+
assert Enum.sum([[1.1], [2.2], [3.3]], &hd/1) == 6.6
1315+
assert Enum.sum([[-3], [-2], [-1], [0], [1], [2], [3]], &hd/1) == 0
1316+
1317+
assert Enum.sum(1..3, &(&1 ** 2)) == 14
1318+
1319+
assert_raise ArithmeticError, fn ->
1320+
Enum.sum([[{}]], &hd/1)
1321+
end
1322+
1323+
assert_raise ArithmeticError, fn ->
1324+
Enum.sum([[1], [{}]], &hd/1)
1325+
end
1326+
end
1327+
13101328
test "product/1" do
13111329
assert Enum.product([]) == 1
13121330
assert Enum.product([1]) == 1

0 commit comments

Comments
 (0)