Use Enum

Hi all

How can I configure it out, if a data abstraction is enumerable or not, for example map? I know map has the implement the enumerable protocol, but where can I find the information?

1 Like

If you want to use Enum module with a given data structure/abstraction, it has to implement Enumberable protocol. So if given data structure implements Enumerable protocol you can use it with Enum.

At least I think that’s how it is :wink:

But how can I configure it out, if the data abstraction is enumerable?

Look at it’s implementation i guess.

There is no easy way to retrieve this information today. Your best bet is to try to invoke a function, such as Enum.to_list(data_type).

I have opened up an issue so we make it a bit more accessible:


Can’t it be done with Protocol.assert_impl!/2? If Enum is a protocol that must be implemented then this function should check if it is implemented. Or am I thinking wrong about this?

This will crash your program is the corresponding module for the datatype you want to check is not loaded. So you need to do an additional step to make sure that the datatype module and the protocol module are already loaded.

1 Like

To be clear, it will crash the process calling assert_impl!, not your full program. Not trying to nitpick, I just don’t want to confuse new people here who may be alarmed that the VM will die if they try to assert_impl!

1 Like

Of course you are right. And my auto correction is not :blush:

1 Like

For those running 1.3 or bellow, here’s how i have done it in the past.
It uses the trick that @josevalim mentions, but optimized.

Just so everyone is aware:

The issue that José mentioned above has been merged into the language. So in the next version of Elixir (or right now if you build from source), you will see information about what protocols something implements when using the i helper in IEx (such as i List), as well as seeing what data structures implement a certain protocol (using e.g. i Enumerable).



awesome work guys.

If you are trying to figure out if a specific protocol is implemented for a specific instance, I believe you can use:

foo = %{} 
if Enumerable.impl_for(foo) do
  IO.puts "Yay!"