Enumerable implementation

76 views
Skip to first unread message

Jay Hayes

unread,
Oct 12, 2016, 11:06:25 AM10/12/16
to elixir-lang-core
Today I'm studying Elixir protocols and stumbled upon something I found curious.

Enumerable came to mind pretty quickly for me as a good example for protocols. The interesting thing that I noticed is the default implementations of Enumerable for Elixir types is a little underwhelming. In particular count/1 and member?/2 aren't even implemented on the protocol. As it turns out, I discovered that _many_ Enum functions for lists in Enum directly instead of in terms of the protocol (e.g. https://github.com/elixir-lang/elixir/blob/c07c345c3c7f2c48531ffe441099c755e34a3679/lib/elixir/lib/enum.ex#L2690-L2700). Of course, I understand that the behavior is OK as is, but it seems to create a little confusion for me about the purpose of the protocol in addition to be a bad example.

I have some suspicion that there might be an optimization involved here, but I'm curious to hear more about the reason for this design. Also, I'd love to take a shot at any improvements that might be involved.

Thanks!

José Valim

unread,
Oct 12, 2016, 12:48:12 PM10/12/16
to elixir-l...@googlegroups.com
It is for optimization purposes. We could implement all? on top of the reduce but that would imply dispatching to the protocol, then to the implementation and then process the reduce operation. So we skip all of that by dispatching to the local implementation.

Another way to put it: sometimes you will find non-idiomatic code in Elixir codebase so *you* don't have to write non-idiomatic code. :)

The other (possibly conflicting) idea is that those could be part of the protocol itself but that would make the protocol unnecessarily large. I do expect the Enumerable protocol to grow though at some point, specially if we end-up implementing a queue/array/vector abstraction.



José Valim
Skype: jv.ptec
Founder and Director of R&D

--
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-core+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/05049472-813d-42af-ad18-67ff8da5d2e0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages