list 将元素添加到列表末尾的最简单方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6732524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the easiest way to add an element to the end of the list?
提问by SoftTimur
As:: : 'a -> 'a list -> 'a list
is used to add an element to the beginof a list, Could anyone tell me if there is a function to add an element to the endof a list? If not, I guess List.rev (element::(List.rev list))
is the most straightforward way to do it?
由于:: : 'a -> 'a list -> 'a list
用于将元素添加到列表的开头,有人能告诉我是否有将元素添加到列表末尾的函数吗?如果没有,我想List.rev (element::(List.rev list))
是最直接的方法吗?
Thank you!
谢谢!
回答by Chris Conway
The reason there's not a standard function to do this is that appending at the end of a list is an anti-pattern(aka a "snoc list" or a Schlemiel the Painter algorithm). Adding an element at the end of a list requires a full copyof the list. Adding an element at the front of the list requires allocating a single cell—the tail of the new list can just point to the old list.
没有标准函数来执行此操作的原因是在列表末尾追加是一种反模式(又名“snoc 列表”或Schlemiel the Painter 算法)。在列表末尾添加元素需要列表的完整副本。在列表的前面添加一个元素需要分配一个单元格——新列表的尾部可以只指向旧列表。
That said, the most straightforward way to do it is
也就是说,最直接的方法是
let append_item lst a = lst @ [a]
回答by Adi
list@[element]
should work. @
joins lists.
list@[element]
应该管用。@
加入列表。
回答by gasche
Given that this operation is linear, you should not use it in the "hot" part of your code, where performance matters. In a cold part, use list @ [element]
as suggest by Adi
. In a hot part, rewrite your algorithm so that you don't need to do that.
鉴于此操作是线性的,您不应在代码的“热”部分使用它,因为这里的性能很重要。在寒冷的部分,list @ [element]
按照 的建议使用Adi
。在热门部分,重写您的算法,这样您就不需要这样做了。
The typical way to do it is to accumulate results in the reverseorder during processing, and then reverse the whole accumulated list before returning the result. If you have N processing steps (each adding an element to the list), you therefore amortize the linear cost of reverse over N elements, so you keep a linear algorithm instead of a quadratic one.
典型的做法是在处理过程中以相反的顺序累加结果,然后在返回结果之前将整个累加列表反转。如果您有 N 个处理步骤(每个都向列表中添加一个元素),那么您将在 N 个元素上分摊反向的线性成本,因此您保留一个线性算法而不是二次算法。
In some case, another technique that work is to process your elements in reverseorder, so that the accumulated results turn out to be in the right order without explicit reversal step.
在某些情况下,另一种有效的技术是以相反的顺序处理您的元素,这样累积的结果就会变成正确的顺序,而无需明确的反转步骤。