Consider the following code:
a = "abcd"
if true do
a = "ijk"
end
f = fn() ->
a = "fn"
end
f.()
IO.puts a
In this example, a
will be printed as ijk
. Elixir also gives the following 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.
I know Elixir is lexically scoped. That’s why the anonymous function could not change the value of a
in the outer scope. But the question is how come it is changing inside the if
block? And why Elixir gives an unsafe warning?
I think it is something to do with if
being a macro. But I am not able to explain it properly. Any help to understand this better would be appreciated.