Dusty

Dusty

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?

Showing Posts 1 to 5

henrik

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}
jmurphyweb

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)
jmurphyweb

jmurphyweb

@Dusty as a general rule, if you are trying to transform one enumerable into another and there is not a direct mapping (where Enum.map would be useful), then it can be done with Enum.reduce.

Often the shape/type of what you want to return will be passed in as the accumulator.

There’s a nice practice exercise that you can try, which is to ‘recreate’ Enum.map, Enum.filter etc using Enum.reduce (which I think is more or less how most Enum functions are built if you check the Elixir source code on Github).

Dusty

Dusty OP

@henrik @jmurphyweb

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.

Oliver

Oliver

Hi, Dusty.

Maps make useful accumulators for Enum.reduce/3, especially if you are interested in doing something for some of the items, or if the previously worked on items are needed in some form.

Another application is passing the whole state of my OTP process into the reduce so it can be used when modifying the enum or reading from it and even be updated while doing so, allowing state-sensitive functions to work on an enumerable. It depends what information you need to use and retain.

def handle_info({:message_with_list, list}, state) do
  state = Enum.reduce(list, state, &function_that_uses_state_and_list/2)
  {:noreply, state}
end

def handle_info({:more_complex, list}, state) do
  {state, modifed_list} = Enum.reduce(list, state, &function_that_uses_state_and_list/2)
  [...]
  {:noreply, state}
end

Etc.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
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
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews