【发布时间】:2018-11-24 18:15:54
【问题描述】:
我是 Elixir 的新手,所以我对这三个陈述有点困惑
a = [ [ 1, 2, 3 ] ]
[a] = [ [ 1, 2, 3 ] ]
[[a]] = [ [ 1, 2, 3 ] ]
第一个和第二个语句按预期返回结果,但第三个语句抛出错误
** (MatchError) 右侧值不匹配:[[1, 2, 3]]
我想知道第三句为什么会报错
【问题讨论】:
标签: elixir
我是 Elixir 的新手,所以我对这三个陈述有点困惑
a = [ [ 1, 2, 3 ] ]
[a] = [ [ 1, 2, 3 ] ]
[[a]] = [ [ 1, 2, 3 ] ]
第一个和第二个语句按预期返回结果,但第三个语句抛出错误
** (MatchError) 右侧值不匹配:[[1, 2, 3]]
我想知道第三句为什么会报错
【问题讨论】:
标签: elixir
a 匹配任何值。 [a] 匹配只包含一个元素的列表,该元素可以是任何值。 [[a]] 匹配一个正好包含一个元素的列表,该列表包含另一个正好一个元素的列表,可以是任何值。
表达式[[1, 2, 3]] 匹配前两个模式,但不匹配第三个,因为它是一个包含三个元素的列表。
【讨论】:
虽然@Dogbert 的回答解释了为什么它不适用于后一种情况,但以下是它如何工作的示例:
iex|1 ▶ [[a, _, _]] = [ [ 1, 2, 3 ] ]
#⇒ [[1, 2, 3]]
iex|2 ▶ [[^a, 2, 3]] = [ [ 1, 2, 3 ] ]
#⇒ [[1, 2, 3]]
iex|3 ▶ a
#⇒ 1
还要注意第 2 行中的Kernel.SpecialForms.^/1 pin 运算符:它基本上强制已经绑定的变量a 匹配而不是回弹。
【讨论】:
为了进一步放大这一点,请考虑:
a = [[1,2,3]]
# a is [[1,2,3]]
[ a ] = [ [1,2,3] ]
^ ^ ^ ^ These match.
#a is [1,2,3]
[ [ a ] ] = [ [ 1,2,3 ] ]
^ ^ ^ ^ ^ ^ ^ ^ These match as well.
# You can consider that the parts that match on the left and the right of
# the pattern match operator are effectively discarded and then elixir attempts to assign
# the remaining portion on the right side to the remaining portion on the left side.
# Hence on the last expression it's trying to assign 1,2,3 to a. The pattern doesn't match
# because you have three values on the right but only one name on the left to bind to.
我希望这可能有助于澄清情况。 @Dogbert 和 @mudasobwa 都是完全正确的;我只是希望这有助于使情况更加清晰。
【讨论】: