kalindkaria

kalindkaria

Map.update inside for loop

Hi, I’ve just started learning Elixir.
For one of the applications I’m developing, I have the following code:

use Bitwise
sensor_data = %{sensor1: 0}
for n <- 0..9, do: sensor_data = Map.update!(sensor_data, :sensor1, &(&1 ||| (1 <<< n)))

This produces following output:

[
  %{sensor1: 1},
  %{sensor1: 2},
  %{sensor1: 4},
  %{sensor1: 8},
  %{sensor1: 16},
  %{sensor1: 32},
  %{sensor1: 64},
  %{sensor1: 128},
  %{sensor1: 256},
  %{sensor1: 512}
]

But the expected output should be:

[
  %{sensor1: 1},
  %{sensor1: 3},
  %{sensor1: 7},
  %{sensor1: 15},
  %{sensor1: 31},
  %{sensor1: 63},
  %{sensor1: 127},
  %{sensor1: 255},
  %{sensor1: 511},
  %{sensor1: 1023}
]

If I run the following statement in iex session the sensor_data map gets updated like this:

sensor_data = Map.update!(sensor_data, :sensor1, &(&1 ||| (1 <<< 0)))
%{sensor1: 1}
sensor_data = Map.update!(sensor_data, :sensor1, &(&1 ||| (1 <<< 1)))
%{sensor1: 3}
sensor_data = Map.update!(sensor_data, :sensor1, &(&1 ||| (1 <<< 2)))
%{sensor1: 5}

Can you help me understand why does the Map.update!/3 doesn’t work inside a for loop?
I also tried with Map.update/4 Map.replace!/3 but no luck.

Most Liked

stefanchrobot

stefanchrobot

The “assignment” inside the for loop has no effect, it creates a new variable on each loop iteration. I think you might be looking for Enum.reduce:

Enum.reduce(0..9, %{sensor1: 0}, fn n, sensor_data ->
  Map.update!(sensor_data, :sensor1, &(&1 ||| (1 <<< n)))
end)
LostKobrakai

LostKobrakai

If you really want to use for you can. Since a few versions back it also supports reductions.

use Bitwise
sensor_data = %{sensor1: 0}
new_sensor_data = 
  for n <- 0..9, reduce: sensor_data do
    acc -> Map.update!(acc, :sensor1, &(&1 ||| (1 <<< n)))
  end
stefanchrobot

stefanchrobot

See also: https://elixir-lang.org/getting-started/case-cond-and-if.html#if-and-unless

This is also a good opportunity to talk about variable scoping in Elixir. If any variable is declared or changed inside if, case, and similar constructs, the declaration and change will only be visible inside the construct. For example:

iex> x = 1
1
iex> if true do
...>   x = x + 1
...> end
2
iex> x
1

In said cases, if you want to change a value, you must return the value from the if:

iex> x = 1
1
iex> x = if true do
...>   x + 1
...> else
...>   x
...> end
2
kokolegorille

kokolegorille

Not only, You also need the previous value.

That’s why You need the acc of a reducer…

kalindkaria

kalindkaria

Thanks @LostKobrakai and @kokolegorille !
I missed out this :reduce option in Comprehensions. I am able to recall now.
Documentation about :reduce for anyone to refer in future:
https://hexdocs.pm/elixir/Kernel.SpecialForms.html#for/1-the-reduce-option

Where Next?

Popular in Chat/Questions Top

xgilarb
Hi there, I’m interested in using Elixir because of the rumors about the reliability of the Phoenix framework, and surprisingly, Elixir’...
New
loganhelms
A while back, I read a great book by Luis Atencio titled, Functional Programming in JavaScript. In section 7.3, he discusses memoization ...
New
Yoga
Or at least, in the works? All I can find are bits and pieces but not a single project from start to finish. Including things like i18n,...
New
mchean
I was wondering if anyone is using some learning tools that they can recommend? I’ve been looking at two specifically so would also be ...
New
KSingh1980
How to run the random query and get the result in JSON format and send it as a response. The query will be in the following form DB Name...
New
ericdouglas
I think that would be really interesting to have official books created by the community about all kinds of development we can do with El...
New
TwistingTwists
I want to learn DSL. Don’t know how to write one. What;s the best introductory resource? I see some macro being used here. Is DSL only ...
New
woohaaha
I’m coming from Ruby and Rails. I have read some Elixir and Phoenix books. They shed a lot of light about building applications in Elixir...
New
miguelsrrobo
hi i was wondering if it is necessary to learn erlang to learn elixir
New
zervis
Hello, I’m about to dive into web development. I was thinking about Laravel or Ruby on Rails, but then I found Phoenix. Do you recommen...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New

We're in Beta

About us Mission Statement