[Question] Enumerable protocol implementation for List inconsistent with Maps

55 views
Skip to first unread message

Sayan Chakraborty

unread,
Sep 7, 2020, 7:51:52 PM9/7/20
to elixir-lang-core
I came across this piece of code which does Enumerable protocol implementation for Lists - https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/enum.ex#L3761-L3763

Consequently, some lines below the same implementation of Maps have this - https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/enum.ex#L3783-L3798

Curious why Lists should return error while Maps return values being part of the same protocol implementation.

sabi...@gmail.com

unread,
Sep 7, 2020, 7:59:07 PM9/7/20
to elixir-lang-core
I believe it is relying on the default reduce-based implementation for lists (because a loop cannot be avoided for linked lists) while there is a more efficient way for maps to count or check memberships.

It is explained in the Enumerable documentation here: https://hexdocs.pm/elixir/Enumerable.html
This protocol requires four functions to be implemented, reduce/3, count/1, member?/2, and slice/1. The core of the protocol is the reduce/3 function. All other functions exist as optimizations paths for data structures that can implement certain properties in better than linear time.

Sayan Chakraborty

unread,
Sep 8, 2020, 3:37:25 AM9/8/20
to elixir-lang-core
Thanks for the reply. But isn't lenght(list), :lists.member(element, enumerable) better alternative here?

its what's being invoked in their namesake functions in Enum module atleast for Lists
Reply all
Reply to author
Forward
0 new messages