【发布时间】:2020-01-15 00:01:13
【问题描述】:
我正在学习 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 的值作为 2。但是由于范围规则,它不存在于它之外。
-
@mttpgn 为什么不将
{1, 2, 3}与{1, x, 3}代码交换?