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?
Thanks
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?
Thanks
If you want to use Enum module with a given data structure/abstraction, it has to implement http://elixir-lang.org/docs/stable/elixir/Enumerable.html 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
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: https://github.com/elixir-lang/elixir/issues/5239.
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.
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!
Of course you are right. And my auto correction is not
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!"
end