In OCaml, for list, we always do first::rest. it is convenient to get the first element out of a list, or insert an element in front of a list.
But why does OCaml not have rest::last? Without List‘s functions, we can’t easily do getting last element of a list or insert an element to the end of a list.
The list datatype is not a magic builtin, only a regular recursive datatype with some syntactic sugar. You could implement it yourself, using
Nilinstead of[]andCons(first,rest)instead offirst::rest, in the following way:I’m not sure if you will see the definition above as an answer to your question, but it really is: when you write
first::rest, you’re not calling a function, you’re just using a datatype constructor that builds a new value (in constant time and space).This definition is simple and has clear algorithmic properties: lists are immutable, accessing the first element of the list is
O(1), accessing thek-th element isO(k), concatenation of two listsli1andli2isO(length(li1)), etc. In particular, accessing the last element or adding something at the end of a listliwould beO(length(li)); we’re not eager to expose this as a convenient operation because it is costly.If you want to add elements at the end of a sequence, lists are not the right data structure. You may want to use a queue (if you follow a first-in, first-out access discipline), a
deque, etc. There is a (mutable)Queuestructure in the standard library, and the two third-party overlays Core and Batteries have a deque module (persistent in Batteries, mutable in Core).