belteconti

belteconti

How to update boolean value of a variable inside if statements?

Hey! Basically, what I am trying to do is update a boolean variable inside an if statement. What I’m currently doing is the following:

defmodule MyModule do

  def my_function() do
   curr1 = curr2 = true
   if a > b do
       curr1 = false
   else
       curr2 = false

     curr1 or curr2
   end
  end
end

The problem over here is that neither curr1 nor curr2 gets updated. Does anyone know we can update the values?

Most Liked

al2o3cr

al2o3cr

Rebinding variables (what happens when you write a = 1 followed by a = 2 later in the same block) is always scoped to the current block and does not “leak” into the surrounding context. That’s why your first example doesn’t work:

def my_function() do
  curr1 = curr2 = true

  if a > b do
    # This _rebinds_ the name "curr1" but only until the "else"
    curr1 = false
  else
    curr2 = false
  end

  # This refers to the original binding, not the one introduced inside the "if" blocks
  curr1 or curr2
end

Same thing for the Enum.map case; each invocation of the anonymous function passed to Enum.map binds curr1 and curr2 and then those bindings are dropped at the end of the function.

Depending on your specific needs, a function like Enum.any? or similar might be a better fit; alternatively, Enum.reduce will do what you’re looking for:

# Ruby version, that uses "leaky" scopes
curr1 = nil
curr2 = nil
some_list.map { |el| curr1, curr2 = something_with(el, curr1, curr2) }
# read the last values stored in curr1 and curr2 here

# Elixir version that makes the shared state between iterations explicit
{curr1, curr2} = Enum.reduce(some_list, {nil, nil}, fn el, {a1, a2} -> something_with(el, a1, a2); end)

Enum.reduce provides the equivalent of an “update” to the accumulated state as the list is traversed.

LostKobrakai

LostKobrakai

Elixir is lexically scoped, so variables of outer scopes are accessible to inner scopes (though not changeable as you’ve seen). Anonymous functions, branching (case/if) or blocks like do/end create new scopes. In your case you try to access variables of an inner scope from the outside, which is not possible. If you need values from inside the anonymous function you need to figure out a way to have it returned by the Enum.map or other function call, which executes the anonymous function.

belteconti

belteconti

Thank you! This helped a lot and I was able to make it work using Enum.reduce and Maps.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
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
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
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
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement