#Help understanding scope and assignment
2 messages · Page 1 of 1 (latest)
Elixir is immutable language, so these xes are in fact different variables. Imagine this like:
x@1 = 0
case {1, 2, 3} do
{4, 5, 6} ->
IO.puts("This clause won't match")
{1, x_value, 3} ->
x@2 = x_value
_ ->
IO.puts("This clause would match any value")
end
# Here, I want x to be 2, not 0
IO.puts(x) # 0
If you want to "expose" that binding to the outside scope, then you need to create new binding in the outside scope like that:
x = 0
x = case {1, 2, 3} do
{4, 5, 6} ->
IO.puts("This clause won't match")
{1, x_value, 3} ->
x_value
_ ->
IO.puts("This clause would match any value")
end
# Here, I want x to be 2, not 0
IO.puts(x) # 0
You cannot alter existing binding (you can only shadow it)