首页 > 解决方案 > 无法在 elixir-lang 的案例指南中使用第一个示例

问题描述

我正在学习 Elixir 并且对它非常陌生。我正在尝试在https://elixir-lang.org/getting-started/case-cond-and-if.html上按照以下示例进行案例陈述。该页面具有以下内容:

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"

当我逐字运行此示例时,我看到以下输出:

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)> 

我在看什么?我期望能够将 x 的值检索为 2。

如果它是相关的,这是我正在使用的版本:IEx 1.9.4 (compiled with Erlang/OTP 22)

标签: pattern-matchingelixir

解决方案


如果您希望 x 在 case 范围之外,则可以将其返回:

{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

推荐阅读