pattern-matching - 无法在 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)
解决方案
如果您希望 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
推荐阅读
- python - Python - 如何更改默认的 os.sep?
- c++ - 如何在 SDI 应用程序的视图中插入多个 FormView
- javascript - Ajax 验证和 SyntaxError: JSON Parse error: Unrecognized token '<' on Laravel
- excel - ColA 和 ColC 中的重复值
- c++ - 为什么函数给了我错误的号码?
- linux - gzip -l 返回未压缩文件大小的错误值
- python - 删除/删除 PyQtGraph 中的图例
- android - 多次在收藏列表中添加相同的项目
- c - 如何在 C 代码中使用 `&&` 和 `;` 等 shell 运算符
- amazon-web-services - 如何在 AWS (elasticbeanstalk) 中为我的 SaaS 用户自定义域设置 SSL?