为什么我不能在 Elixir 闭包函数头中使用 pin 运算符?
Why can't I use the pin operator in an Elixir closure function head?
通常在 Elixir 中,我可以使用 pin 运算符来指定绑定到现有名称的值,即:
a = 1
{^a, b} = {1,2}
# b is now 2
按预期工作。
但是我似乎无法在闭包函数头中固定这样的值,即:
a = 1
f = fn
^a -> true
_ -> false
end
导致编译失败:
** (CompileError) iex:2: unbound variable ^a
这是否有原因,以及获得相同结果的正确方法?
谢谢
上述问题的解决方法似乎是在闭包内使用 case 语句,尽管感觉不必要地复杂。
a = 1
f = fn n ->
case n do
^a -> true
_ -> false
end
end
f.(1)
# true
f.(2)
# false
虽然这有效,但它强调了我不能直接在 fn 头中使用 pin 运算符是多么奇怪。
这直接来自何塞对另一个问题发布的回答:
Elixir allows rebinding only in the same scope and all constructs, with the exception of case, cond and receive, introduce a new scope.
因此您无法固定 a,因为它是一个新范围。
您的代码在概念上没有任何错误。它不起作用,因为它是当前 Elixir 版本的限制,将在 Elixir v1.2 中解决。
您可以通过以下方式获得相同的结果:
a = 1
f = fn
new_a when a === new_a -> true
_ -> false
end
通常在 Elixir 中,我可以使用 pin 运算符来指定绑定到现有名称的值,即:
a = 1
{^a, b} = {1,2}
# b is now 2
按预期工作。
但是我似乎无法在闭包函数头中固定这样的值,即:
a = 1
f = fn
^a -> true
_ -> false
end
导致编译失败:
** (CompileError) iex:2: unbound variable ^a
这是否有原因,以及获得相同结果的正确方法?
谢谢
上述问题的解决方法似乎是在闭包内使用 case 语句,尽管感觉不必要地复杂。
a = 1
f = fn n ->
case n do
^a -> true
_ -> false
end
end
f.(1)
# true
f.(2)
# false
虽然这有效,但它强调了我不能直接在 fn 头中使用 pin 运算符是多么奇怪。
这直接来自何塞对另一个问题发布的回答:
Elixir allows rebinding only in the same scope and all constructs, with the exception of case, cond and receive, introduce a new scope.
因此您无法固定 a,因为它是一个新范围。
您的代码在概念上没有任何错误。它不起作用,因为它是当前 Elixir 版本的限制,将在 Elixir v1.2 中解决。
您可以通过以下方式获得相同的结果:
a = 1
f = fn
new_a when a === new_a -> true
_ -> false
end