gpt4 book ai didi

Elixir:这是什么样的列表,但竖线仍在其中?

转载 作者:行者123 更新时间:2023-12-04 14:10:24 24 4
gpt4 key购买 nike

我正在研究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

那些我得到的。但是 这是什么
l = ["hi" | "there"] #=> ["hi" | "there"]

它似乎是一个带有头部和尾部的列表:
is_list(["hi" | "there"]) #=> true
hd(["hi" | "there"]) #=> "hi"
tl(["hi" | "there"]) #=> "there"

...但是如果给定这样的列表, length(list)函数会给出一个 ArgumentError

它是做什么用的?

最佳答案

列表不正确是正确的。

我会引用Learn You Some Erlang的注释,将其总结得很好。

Note: Using the form [1 | 2] gives what we call an 'improper list'. Improper lists will work when you pattern match in the [Head|Tail] manner, but will fail to be used with standard functions of Erlang (even length()). This is because Erlang expects proper lists. Proper lists end with an empty list as their last cell. When declaring an item like [2], the list is automatically formed in a proper manner. As such, [1|[2]] would work! Improper lists, although syntactically valid, are of very limited use outside of user-defined data structures.

关于Elixir:这是什么样的列表,但竖线仍在其中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36946064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com