-->

What is the easiest way to add an element to the e

2020-08-10 07:07发布

问题:

As:: : 'a -> 'a list -> 'a list is used to add an element to the begin of a list, Could anyone tell me if there is a function to add an element to the end of a list? If not, I guess List.rev (element::(List.rev list)) is the most straightforward way to do it?

Thank you!

回答1:

list@[element] should work. @ joins lists.



回答2:

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 copy of 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.

That said, the most straightforward way to do it is

let append_item lst a = lst @ [a]


回答3:

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.

The typical way to do it is to accumulate results in the reverse order 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.

In some case, another technique that work is to process your elements in reverse order, so that the accumulated results turn out to be in the right order without explicit reversal step.



标签: list ocaml