Why is appending to a list bad?

前端 未结 5 1255
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 01:18

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 state

5条回答
  •  佛祖请我去吃肉
    2020-12-01 01:42

    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, singly linked list.

    If doubly 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 singly linked lists.

    Regarding the second question: You can use ::: to concatenate a single-element list to the end of your list. This is an O(n) operation.

    List(1,2,3) ::: List(4)
    

提交回复
热议问题