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)
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With