The :: operator in F# always prepends elements to the list. Is there an operator that appends to the list? I'm guessing that using @ operator
[1; 2; 3] @ [4]
would be less efficient, than appending one element.
The :: operator in F# always prepends elements to the list. Is there an operator that appends to the list? I'm guessing that using @ operator
[1; 2; 3] @ [4]
would be less efficient, than appending one element.
I'm guessing that using @ operator [...] would be less efficient, than appending one element.
If it is, it will be a negligible difference. Both appending a single item and concatenating a list to the end are O(n)
operations. As a matter of fact I can't think of a single thing that @
has to do, which a single-item append function wouldn't.
The efficiency (or lack of) comes from iterating through the list to find the final element. So declaring a new list with [4]
is going to be negligible for all but the most trivial scenarios.
As others said, there is no such operator, because it wouldn't make much sense. I actually think that this is a good thing, because it makes it easier to realize that the operation will not be efficient. In practice, you shouldn't need the operator - there is usually a better way to write the same thing.
Typical scenario: I think that the typical scenario where you could think that you need to append elements to the end is so common that it may be useful to describe it.
Adding elements to the end seems necessary when you're writing a tail-recursive version of a function using the accumulator parameter. For example a (inefficient) implementation of filter
function for lists would look like this:
let filter f l =
let rec filterUtil acc l =
match l with
| [] -> acc
| x::xs when f x -> filterUtil (acc @ [x]) xs
| x::xs -> filterUtil acc xs
filterUtil [] l
In each step, we need to append one element to the accumulator (which stores elements to be returned as the result). This code can be easily modified to use the ::
operator instead of appending elements to the end of the acc
list:
let filter f l =
let rec filterUtil acc l =
match l with
| [] -> List.rev acc // (1)
| x::xs when f x -> filterUtil (x::acc) xs // (2)
| x::xs -> filterUtil acc xs
filterUtil [] l
In (2), we're now adding elements to the front of the accumulator and when the function is about to return the result, we reverse the list (1), which is a lot more efficient than appending elements one by one.
Lists in F# are singly-linked and immutable. This means consing onto the front is O(1) (create an element and have it point to an existing list), whereas snocing onto the back is O(N) (as the entire list must be replicated; you can't change the existing final pointer, you must create a whole new list).
If you do need to "append one element to the back", then e.g.
l @ [42]
is the way to do it, but this is a code smell.