Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to add an element to the end of the list?

Tags:

list

ocaml

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!

like image 403
SoftTimur Avatar asked Jul 18 '11 11:07

SoftTimur


People also ask

How do I add elements to the end of a list?

If we want to add an element at the end of a list, we should use append . It is faster and direct. If we want to add an element somewhere within a list, we should use insert . It is the only option for this.

How do you add a string to the end of a list in Python?

Adding a string to a list inserts the string as a single element, and the element will be added to the list at the end. The list. append() will append it to the end of the list. You can refer to the below screenshot to see the output for add string to list python.


2 Answers

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]
like image 152
Chris Conway Avatar answered Nov 02 '22 06:11

Chris Conway


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

like image 31
Adi Avatar answered Nov 02 '22 06:11

Adi