vrod

vrod

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!

Showing Posts 1 to 10

seanmor5

seanmor5

Author of Genetic Algorithms in Elixir

Why not just use Map.from_struct/1?

a = %MyStruct{foo: 0, bar: 1}
a
|> Map.from_struct()
|> Enum.count()
eksperimental

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

vrod

vrod OP

2 reasons I cannot use from_struct:

  1. the code that calls this is in 3rd party package – I cannot pre-change my struct
  2. academic. I want to know how to do this – all the posts I see in the forum seem to be how to avoid doing this
srowley

srowley

Speaking totally naively, it seems like you could start with the implementation for maps, and then just add a step for each callback that addresses how the {:__struct__, ModuleName} key/value pair that is a part of every struct is handled. I can imagine cases where you might want to ignore it, and other cases where you would not.

I would not be surprised if that is wrong/missing something, but that is where I would start and maybe others can speak to why that would/wouldn’t be a good idea.

vrod

vrod OP

Thank you all for the suggestions! @eksperimental this source code was very helpful and @srowley you are right some decisions must be taken about this :__struct__ key.

For example I tried implementing this with DateTime struct – I found this is almost 100% copy of the source code for Map impl. The only change I tried was in the count function but I understand this may be different depends on what you need to do:

defimpl Enumerable, for: DateTime do
  def count(map) do
    {:ok, map |> Map.from_struct() |> map_size()}
  end

  def member?(map, {key, value}) do
    {:ok, match?(%{^key => ^value}, map)}
  end

  def member?(_map, _other) do
    {:ok, false}
  end

  def slice(map) do
    size = map_size(map)
    {:ok, size, &Enumerable.List.slice(:maps.to_list(map), &1, &2, size)}
  end

  def reduce(map, acc, fun) do
    Enumerable.List.reduce(:maps.to_list(map), acc, fun)
  end
end
eksperimental

eksperimental

This one is wrong, as the result of size will include the :__struct__ key

vrod

vrod OP

Actually my case works even if I return {:error, "no slice"} for this function so I think this means that whatever Enum functions are being used they are not requiring the slice function. I am not sure if this size variable is like the size of “chunk” for getting part of a list? I think maybe sometimes you might want this to include __struct__ key but It most probably depends on the use case. Anyhow I have now at least something that I can play around with. Thank you again!

al2o3cr

al2o3cr

I don’t understand this part - if you’re passing a struct where the third-party code expects an Enumerable, why couldn’t you just… not do that?

eksperimental

eksperimental

Nope. That is not how it works. It is explained in the documentation of each funtion.

eksperimental

eksperimental

Exactly, that’s why I wonder why would you want to implement the Enumerable for DateTime when you are just gonna treat it like a map. You’ d better off convert it to a map.

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews