[Proposal] Enum.sum/2

66 views
Skip to first unread message

Sabiwara Yukichi

unread,
Jul 23, 2021, 12:51:49 AM7/23/21
to elixir-l...@googlegroups.com
Hi!

Recently I found myself several times in a situation where I needed to sum from an enumerable after applying a transformation, e.g. sum one field from a list of structs.
There is a temptation to use Enum.map(list, fun) |> Enum.sum() which would be wasteful since it needs to build the intermediate list.
Enum.reduce(list, 0, &(fun.(&1) + &2) works but it is less straightforward and less explicit about the intent.

I wondered if Enum.sum(list, fun) (or Enum.sum_by(list, fun)?) could be a nice addition that would be consistent with some other Enum functions such as Enum.count/2, Enum.any?/2. What do you think?


José Valim

unread,
Jul 23, 2021, 2:51:16 AM7/23/21
to elixir-l...@googlegroups.com
I have thought about this a couple of times but another discussion we keep having is to make Enum.sum/1 part of a protocol for performance and then we wouldn't be able to optimize it in the Enum.sum/2 variant. I wonder if that can be confusing. So for now, I would go the reduce route if you are really worried about performance here.

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/CANnyohZtg19ES%2B52KzCX%3DYnY-rgaLoNcnuRaCyrmtbMpTQ1NDg%40mail.gmail.com.

Sabiwara Yukichi

unread,
Jul 24, 2021, 3:33:13 AM7/24/21
to elixir-l...@googlegroups.com
I see. Regarding the point about protocol performance optimization, I wonder if this would be that confusing, given this is already the case with Enum.count/1 (optimizeable by Enumerable protocol) VS Enum.count/2 (not optimized)?

But Enum.reduce works fine for my case, so this clearly isn't a blocker or anything :)

Reply all
Reply to author
Forward
0 new messages