Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么[head | tail]语法在用作参数时与Elixir中的单个元素数组匹配?_Elixir - Fatal编程技术网

为什么[head | tail]语法在用作参数时与Elixir中的单个元素数组匹配?

为什么[head | tail]语法在用作参数时与Elixir中的单个元素数组匹配?,elixir,Elixir,我注意到在iex中运行[1]=[head | tail]会导致编译错误。但是,如果定义函数,如: def simple_func([ head | tail ]) do IO.inspect(head) IO.inspect(tail) end 这一论点似乎是一致的。我假设引擎盖下发生了什么事,我很想知道它是什么。尾巴是剩余的列表。在一个参数的列表中,它只是一个空列表,因此它实际上是匹配的。要匹配的模式位于=的左侧,而不是右侧: iex(1)> [head | tail] = [

我注意到在iex中运行
[1]=[head | tail]
会导致编译错误。但是,如果定义函数,如:

def simple_func([ head | tail ]) do
  IO.inspect(head)
  IO.inspect(tail)
end

这一论点似乎是一致的。我假设引擎盖下发生了什么事,我很想知道它是什么。

尾巴是剩余的列表。在一个参数的列表中,它只是一个空列表,因此它实际上是匹配的。

要匹配的模式位于
=
的左侧,而不是右侧:

iex(1)> [head | tail] = [1]
[1]
iex(2)> head
1
iex(3)> tail
[]

有三种情况 1.之前未定义的头部和尾部:

iex(1)> [1] = [head | tail] 
** (CompileError) iex:5: undefined function head/0
    (stdlib) lists.erl:1353: :lists.mapfoldl/3
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
  • 头部和尾部由匹配的值定义
    
    iex(1)>水头=1
    1.
    iex(2)>尾部=[]
    []
    iex(3)>[1]=[头|尾]
    
    在这种情况下,头部和尾部的组合(
    [head | tail]
    )等于如此匹配的
    [1]
    ,并且没有错误

  • 头部和尾部是用不匹配的值定义的

  • `


    在这种情况下,头部和尾部的组合(
    [head | tail]
    )等于
    [2]
    ,因此在发布后立即意识到匹配错误

    ,即我做错了。谢谢你的澄清
    iex(1)> head = 2
    2
    iex(2)> tail = []
    []
    iex(3)> [1] = [head|tail]
    ** (MatchError) no match of right hand side value: [2]