无法在 elixir-lang 的案例指南中使用第一个示例
Can't get the first example to work in elixir-lang's case guide
我正在学习 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)
如果你想要 x 在 case 范围之外,那么你可以 return 它:
{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
我正在学习 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)
如果你想要 x 在 case 范围之外,那么你可以 return 它:
{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