views:

1038

answers:

5

I've recently started learning scala, and I've come across the :: (cons) function, which prepends to a list.
In the book "Programming in Scala" it states that there is no append function because appending to a list has performance o(n) whereas prepending has a performance of o(1)

Something just strikes me as wrong about that statement.

Isn't performance dependent on implementation? Isn't it possible to simply implement the list with both forward and backward links and store the first and last element in the container?

The second question I suppose is what I'm supposed to do when I have a list, say 1,2,3 and I want to add 4 to the end of it?

+1  A: 

Yea in a double linked list appending to the tail is o(1) as well, the book is probably refering to a linked list where there is only a reference to the head object as opposed to both

Daniel
But only when modifying the list. Creating a new list with the new item appended, while keeping the original list intact, would require O(n) even with double linked lists because the list would need to be copied.
sepp2k
+3  A: 

Prepending is faster because it only requires two operations:

  1. Create the new list node
  2. Have that new node point to the existing list

Appending requires more operations because you have to traverse to the end of the list since you only have a pointer to the head.

I've never programmed in Scala before, but you could try a List Buffer

skalburgi
+3  A: 

Most functional languages prominently figure a singly-linked-list data structure, as it's a handy immutable collection type. When you say "list" in a functional language, that's typically what you mean (a singly-linked list, usually immutable). For such a type, append is O(n) whereas cons is O(1).

Brian
+16  A: 

The key is that x :: somelist does not mutate somelist, but instead creates a new list, which contains x followed by all elements of somelist. This can be done in O(1) time because you only need to set somelist as the successor of x in the newly created, single linked list.

If double linked lists were used instead, x would also have to be set as the predecessor of somelist's head, which would modify somelist. So if we want to be able to do :: in O(1) without modifying the original list, we can only use single linked lists.

Regarding the second question: You can do

List(1,2,3) ::: List(4)
sepp2k
+4  A: 

Other answers have given good explanations for this phenomenon. If you are appending many items to a list in a subroutine, or if you are creating a list by appending elements, a functional idiom is to build up the list in reverse order, cons'ing the items on the front of the list, then reverse it at the end. This gives you O(n) performance instead of O(n²).

Chris Conway