【问题标题】:Can't get the first example to work in elixir-lang's case guide无法在 elixir-lang 的案例指南中使用第一个示例
【发布时间】: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} 代码交换?

标签: pattern-matching elixir


【解决方案1】:

如果您希望 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2019-12-12
    • 1970-01-01
    • 2014-10-15
    相关资源
    最近更新 更多