vrod
How to implement Enumerable protocol for struct?
Sorry because many other people asked a similar question… but how do you implement the Enumerable protocol for a struct? I see the docs on https://hexdocs.pm/elixir/master/Enumerable.html but I do not follow how to actually do this… is there an example somewhere? Just to be able to treat my structs the same as maps for many Enum operations. Thank you!
Most Liked
seanmor5
Why not just use Map.from_struct/1?
a = %MyStruct{foo: 0, bar: 1}
a
|> Map.from_struct()
|> Enum.count()
brettbeatty
- the code that calls this is in 3rd party package - I cannot pre-change my struct
I would just echo what the others have said–there might be a way to grab the needed data out of your structs before passing it to the other library. Typically you don’t want to implement protocols for data types for which the protocol doesn’t really make sense (what does it mean to enumerate a datetime?).
- academic. I want to know how to do this
I think the code that really made things click for me was the Enumable implementation for Range.
I also tried writing a blog post about implementing Enumerable for custom data structures, but I don’t know if it’s any clearer.
eksperimental
The best example is the source code itself.
https://github.com/elixir-lang/elixir/blob/ae5188d8996f9ab44358be3d7acd4447a2de0677/lib/elixir/lib/enum.ex#L3986-L4007
But note that you cannot rely on the implementation for maps. The only function that will work is member?/2
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









