Alex Rivera | Logout

cons operator (::) in F#

Asked 2010-03-20T13:15:28.783
55

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.

Edit
Report

1 Answer

36

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.

answered 2010-03-20T17:00:40.630

Your Answer