Elixir:这个垂直条仍在哪个列表中?

Nat*_*ong 6 elixir

我正在挖掘Phoenix如何将模板呈现为iodata,我发现一些看起来很奇怪的列表.似乎我错过了涉及"垂直条"或"垂直管道"字符(|)的列表的基本语法.

下面是一些例子我明白了:

# prepends 1 to the list [2, 3]
l = [1 | [2, 3]] #=> [1, 2, 3]

# matches the head and tail into variables
inspect_tail = fn ([_head | tail]) -> IO.inspect(tail) end
Run Code Online (Sandbox Code Playgroud)

那些我得到的.但这是什么

l = ["hi" | "there"] #=> ["hi" | "there"]
Run Code Online (Sandbox Code Playgroud)

它似乎是一个头尾的列表:

is_list(["hi" | "there"]) #=> true
hd(["hi" | "there"])      #=> "hi"
tl(["hi" | "there"])      #=> "there"
Run Code Online (Sandbox Code Playgroud)

...但是length(list)函数给出了一个ArgumentErrorif这样的列表.

它是什么,它用于什么?

jis*_*one 6

不正确的清单是正确的.

我将引用一些来自Learn You Some Erlang的说明,它总结得很好.

注意:使用表单[1 | 2]会给出我们称之为"不正确的列表"的内容.当您[Head|Tail]以某种方式模式匹配时,不正确的列表将起作用,但将无法与Erlang的标准函数一起使用(甚至是length()).这是因为Erlang期望正确的列表.正确的列表以空列表作为最后一个单元格结束.在声明项目时[2],列表会以适当的方式自动形成.因此,[1|[2]]会工作!不正确的列表虽然在语法上有效,但在用户定义的数据结构之外的使用非常有限.