@@ -3476,9 +3476,9 @@ defmodule Enum do
3476
3476
end
3477
3477
3478
3478
@ doc """
3479
- Maps and sums the given enumerable in one pass.
3479
+ Maps and sums the given ` enumerable` in one pass.
3480
3480
3481
- Raises `ArithmeticError` if `fun ` returns a non-numeric value.
3481
+ Raises `ArithmeticError` if `mapper ` returns a non-numeric value.
3482
3482
3483
3483
## Examples
3484
3484
@@ -3514,6 +3514,8 @@ defmodule Enum do
3514
3514
3515
3515
Raises `ArithmeticError` if `enumerable` contains a non-numeric value.
3516
3516
3517
+ If you need to apply a transformation first, consider using `Enum.product_by/2` instead.
3518
+
3517
3519
## Examples
3518
3520
3519
3521
iex> Enum.product([])
@@ -3530,6 +3532,40 @@ defmodule Enum do
3530
3532
reduce ( enumerable , 1 , & * / 2 )
3531
3533
end
3532
3534
3535
+ @ doc """
3536
+ Maps and computes the product of the given `enumerable` in one pass.
3537
+
3538
+ Raises `ArithmeticError` if `mapper` returns a non-numeric value.
3539
+
3540
+ ## Examples
3541
+
3542
+ iex> Enum.product_by([%{count: 2}, %{count: 4}, %{count: 3}], fn x -> x.count end)
3543
+ 24
3544
+
3545
+ iex> Enum.product_by(1..3, fn x -> x ** 2 end)
3546
+ 36
3547
+
3548
+ iex> Enum.product_by([], fn x -> x.count end)
3549
+ 1
3550
+
3551
+ Filtering can be achieved by returning `1` to ignore elements:
3552
+
3553
+ iex> Enum.product_by([2, -1, 3], fn x -> if x > 0, do: x, else: 1 end)
3554
+ 6
3555
+
3556
+ """
3557
+ @ doc since: "1.18.0"
3558
+ @ spec product_by ( t , ( element -> number ) ) :: number
3559
+ def product_by ( enumerable , mapper )
3560
+
3561
+ def product_by ( list , mapper ) when is_list ( list ) and is_function ( mapper , 1 ) do
3562
+ product_by_list ( list , mapper , 1 )
3563
+ end
3564
+
3565
+ def product_by ( enumerable , mapper ) when is_function ( mapper , 1 ) do
3566
+ reduce ( enumerable , 1 , fn x , acc -> acc * mapper . ( x ) end )
3567
+ end
3568
+
3533
3569
@ doc """
3534
3570
Takes an `amount` of elements from the beginning or the end of the `enumerable`.
3535
3571
@@ -4811,6 +4847,11 @@ defmodule Enum do
4811
4847
defp sum_by_list ( [ ] , _ , acc ) , do: acc
4812
4848
defp sum_by_list ( [ h | t ] , mapper , acc ) , do: sum_by_list ( t , mapper , acc + mapper . ( h ) )
4813
4849
4850
+ ## product_by
4851
+
4852
+ defp product_by_list ( [ ] , _ , acc ) , do: acc
4853
+ defp product_by_list ( [ h | t ] , mapper , acc ) , do: product_by_list ( t , mapper , acc * mapper . ( h ) )
4854
+
4814
4855
## take
4815
4856
4816
4857
defp take_list ( _list , 0 ) , do: [ ]
0 commit comments