mttpgn
mttpgn

Reputation: 372

Can't get the first example to work in elixir-lang's case guide

I'm learning Elixir and very new to it. I'm trying to follow the following example at https://elixir-lang.org/getting-started/case-cond-and-if.html for case statements. That page has the following:

iex> case {1, 2, 3} do
...>   {4, 5, 6} ->
...>     "This clause won't match"
...>   {1, x, 3} ->
...>     "This clause will match and bind x to 2 in this clause"
...>   _ ->
...>     "This clause would match any value"
...> end
"This clause will match and bind x to 2 in this clause"

When I run this example verbatim, I see the following output:

iex(5)> case {1, 2, 3} do
...(5)>   {4, 5, 6} ->
...(5)>     "This clause won't match"
...(5)>   {1, x, 3} ->
...(5)>     "This clause will match and bind x to 2 in this clause"
...(5)>   _ ->
...(5)>     "This clause would match any value"
...(5)> end
warning: variable "x" is unused (if the variable is not meant to be used, prefix it with an underscore)
  iex:8

"This clause will match and bind x to 2 in this clause"
iex(6)> x
** (CompileError) iex:6: undefined function x/0

iex(6)> 

What am I overlooking? I am expecting to be able to retrieve the value of x as 2.

If it's relevant here's the version I'm using: IEx 1.9.4 (compiled with Erlang/OTP 22)

Upvotes: 0

Views: 60

Answers (1)

Daniel
Daniel

Reputation: 2554

If you want x outside of the case scope, then you can just return it:

{x, message} = case {1, 2, 3} do
  {4, 5, 6} -> "This clause won't match"
  {1, x, 3} -> {x, "This clause will match and bind x to 2 in this clause"}
  _ -> "This clause would match any value"
end

iex(5)> x
2

Upvotes: 1

Related Questions