#Help understanding scope and assignment

2 messages · Page 1 of 1 (latest)

lyric loom
#

My problem is explained in the code comments below. Any help is much appreciated.

x = 0

case {1, 2, 3} do
  {4, 5, 6} ->
    IO.puts("This clause won't match")
  {1, x_value, 3} ->
    x = x_value
  _ ->
    IO.puts("This clause would match any value")
end

# Here, I want x to be 2, not 0
IO.puts(x) # 0
hollow olive
#

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)