我是Elixir的新手,所以我对这三个陈述感到困惑
'uname' is not recognized as an internal or external command,
operable program or batch file.
第一个和第二个语句按预期返回结果,但第三个引发错误
**(MatchError)右侧值不匹配:[[1,2,3]]
我想知道第三句为什么会犯错误
答案 0 :(得分:10)
a
匹配任何值。 [a]
匹配包含一个元素的列表,该元素可以是任何值。 [[a]]
匹配一个元素的列表,该列表包含另一个可以是任何值的元素的列表。
表达式[[1, 2, 3]]
与前两个模式匹配,但与第三个模式不匹配,因为它是包含三个元素的一个列表的列表。
答案 1 :(得分:2)
虽然@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
引脚运算符:它基本上强制已绑定的变量a
匹配而非反弹。< / p>
答案 2 :(得分:2)
进一步考虑放大这个:
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都是完全正确的;我希望这有助于使情况更加清晰。