I have this list of maps:
list = [%{price: 2, quantity:4}, %{price: 3, quantity: 5}]
For each map on the list, I need to multiply the price by the quantity and then sum all of the results.
In this case it would be: (2 * 4) + (3 * 5) = 23
I’ve tried many ways but I don’t know how to achieve this. I can’t show what I’ve done before because all of that leads nowhere.
I’d appreciate if anyone knows how to do this. Thanks
Enum.reduce(list, 0, fn %{price: price, quantity: quantity}, acc ->
acc + price * quantity
end)
2 Likes
@Laetitia’s solution is a good one, and it does it in a single pass.
However you could also conceptually split the problem up which might be easier to understand:
list
|> Enum.map(fn %{price: price, quantity: quantity} -> price * quantity end)
|> Enum.sum
This is almost verbatim your problem statement:
For each map on the list, I need to multiply the price by the quantity and then sum all of the results.
The Enum.map
multiplies the price by the quantity, and then Enum.sum adds it all up.
1 Like
Both solutions are great. Both do the job in a very elegant way. Thanks both for your precious time. I tried both solutions and those are great. I’ll implement yours because it’s easier to read, at least for me
Wasn’t there a plan for an official Elixir API like Enum.product
btw?
Thanks.
But hmmm, that doesn’t seem exactly as what OP needs then.
It’s generally helpful to post it anyways, because folks will be able to help troubleshoot your thinking and make future problems easier.
2 Likes
Ok , next time then. Thanks