Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: Set variable in if statement

Tags:

elixir

I'm very new to Elixir and this simple problem is driving me nuts.

a = 0
if true do
    a = 1 + 1
end 
a = a + 1

IO.puts (a)

Interestingly this gives the correct value but also gives a warning:

warning: the variable "a" is unsafe as it has been set inside a case/cond/receive/if/&&/||. Please explicitly return the variable value instead. For example:

case int do
  1 -> atom = :one
  2 -> atom = :two
end

should be written as

atom =
  case int do
    1 -> :one
    2 -> :two
  end

Unsafe variable found at:
  Untitled:5

3

I don't understand the warning message. What is the best way of doing this in Elixir?

Update: What about this condition too?

a = 0
b = 0
if true do
    a = 1 + 1
    b = 2 + 2
end 
a = a + 1
b = b + 2

IO.puts (a)
IO.puts (b)
like image 476
iphaaw Avatar asked Sep 17 '16 19:09

iphaaw


2 Answers

In Elixir every statement returns the value. Instead of assigning variable in if you can assign whole if statement value into variable.

a = 0
a = if true do
      1 + 1
    else
      a + 1
    end
like image 141
PatNowak Avatar answered Sep 24 '22 01:09

PatNowak


The warning is correct trying to prevent you from doing _ possibly dangerous_ thing. It is very well explained in the Elixir's 1.3 changelog.

Take a look at Deprecation of imperative assignment section, where it is explained (with example) here:

http://elixir-lang.org/blog/2016/06/21/elixir-v1-3-0-released/

Hope that helps!

like image 28
Paweł Dawczak Avatar answered Sep 24 '22 01:09

Paweł Dawczak