1
votes

I'm learning Elixir and am having trouble with a concept. Consider the following code:

iex(3)> case 1 do              
...(3)> x -> "x exists"        
...(3)> _ -> "something exists"
...(3)> end
"x exists"
iex(4)> x
** (CompileError) iex:4: undefined function x/0

The variable x isn't bound to anything yet, then how does the first case expression match? I thought it might be because Elixir is different from Erlang when it comes to assignment and so perhaps x gets bound in the process, but the command #4 shows that x isn't bound.

1

1 Answers

1
votes

Values bound in the patterns or body of a case expression are only available inside that branch.

case 1 do
  x -> IO.puts(x)
end

will print

1

If you want to extract a value from a case, you can store the return value of the case call:

x = case 2 do
  1 -> 2
  2 -> 3
  _ -> 0
end

x #=> 3