Dusty
Passing an updated struct to each iteration of Enum
I am trying to iterate over a map, and repeatedly update a struct using each {k, v} pair in the map. But I am having difficulty figuring out how to pass the new/updated struct to the next iteration of the function. So I have something like:
struct = %MyStruct{...}
map = %{key1: value1, key2: value2,...}
def my_func(struct, key, value) do
struct = # some code that updates the struct using the key and value
struct # return the new struct
end
and I am trying to do something like:
struct = Enum.each(map, fn {key, value} -> my_func(struct, key, value) end)
{:ok, struct}
Obviously that code does not work, because Enum.each/2 returns :ok, but doesn’t carry the updated struct into the next iteration of the function, and doesn’t return the struct itself. It seems like I need a form of Enum.reduce/3 where the struct acts as the accumulator. How would you approach this?
Most Liked
henrik
Hi Dusty!
You could indeed use Enum.reduce/3:
iex> fake_struct = %{x: 0}
%{x: 0}
iex> map = %{key1: 1, key2: 2}
%{key1: 1, key2: 2}
iex> Enum.reduce(map, fake_struct, fn ({_k, v}, s) -> %{s | x: s.x + v} end)
%{x: 3}
Dusty
Thank you both for your time. It appears I just need a broader mental definition of an accumulator. Examples of reduce that I’ve seen always seem to use simple structures (like integer values) as an accumulator, but if the struct itself can be the accumulator then I think I’m in good shape.
jmurphyweb
Usually you would reduce over the map, and use a struct as the accumulator.
Enum.reduce(map, struct, fn {key, val}, new_struct ->
# ... perform some logic
%{new_struct | key: value}
end)
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
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









