TomHale

TomHale

Why assign if/else to a variable?

In Elixir Succinctly I read:

Since everything in Elixir is an expression, and if is no exception, the if…else construct returns a value that we can assign to a variable for later use:

a = if test_conditional do
# ...

What are some practical usages of this?

Most Liked

NobbZ

NobbZ

You can have the value of a variable depending on some condition.

In other languages you see code like the following which would not work in Elixir due to elixirs scoping rules:

a = 2
if condition then:
    a = 1
pavancse17

pavancse17

if suppose you want to change any variable value inside if block in Elixir. You need to get back and re-assign the value to the same variable.

This is the code you will expect to work. But it won’t.

iex(7)> a = 5
5
iex(8)> is_odd = nil
nil
iex(9)> if rem(a, 2) == 0 do
...(9)>   is_odd = false
...(9)> else 
...(9)>   is_odd = true
...(9)> end
warning: variable "is_odd" is unused (if the variable is not meant to be used, prefix it with an underscore)
  iex:12

warning: variable "is_odd" is unused (if the variable is not meant to be used, prefix it with an underscore)
  iex:10

true
iex(10)> is_odd
nil

So you need to re-assign it back like below:

iex(13)> a = 5
5
iex(14)> 
nil
iex(15)> is_odd = if rem(a, 2) == 0 do
...(15)>   false
...(15)> else 
...(15)>   true
...(15)> end
true
iex(16)> is_odd
true
iex(17)> 
NobbZ

NobbZ

There was a warning about the “imperative assignment” from 1.2 or 1.3 on, and it actually worked until 1.8 or 1.9…

Ljzn

Ljzn

Welcome to the immutable data structure land. Most data in elixir is immutable, in other words, you can’t change the value of a variable. Instead, you can create a new const using old name.

iex(1)> a = 1
1
iex(2)> if true, do: a = 2
warning: variable "a" is unused (if the variable is not meant to be used, prefix it with an underscore)
  iex:2

2
iex(3)> a
1  # didn't change

iex(4)> a = if true, do: 2
2  # new value with old name
LostKobrakai

LostKobrakai

That’s not really the case for what you show. Your examples work the way they do, because of the lexical scoping rules within elixir. Earlier versions of elixir (until 1.2 iirc) did work differently and allowed rebinding of variables within if blocks. There’s no mutability in both versions though, as that one is enforced by the beam.

So while it might seem related it actually is not.

Where Next?

Popular in Questions Top

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
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New

We're in Beta

About us Mission Statement