Like you I mostly use Enum.reduce
. When I do reach for the for
comprehension syntax it’s usually to take advantage of how easy it is to combine multiple enumerables into one logic pipeline.
a = [1, 2, 3]
b = [?a, ?b, ?c]
for i <- a, c <- b, i + c == 100, reduce: 0 do
acc -> acc + i + c
end
# 300
versus
a
|> Enum.reduce(0, fn i, acc ->
b
|> Enum.filter(fn c -> c + i == 100 end)
|> Enum.reduce(acc, fn c, accacc ->
accacc + c + i end)
end)
# 300
I suspect it also may seem more familiar to people more comfortable with imperative programming approaches. Finally, there might be some cases where the for
comprehension does provide some performance improvements as per this discussion.