Why are Scala's `Lists` implemented as linked lists

后端 未结 5 1528
闹比i
闹比i 2021-02-19 05:49

I always thought that the benefit of linked lists was that you could add or remove items (especially not from the end) without having to copy lots of elements thanks to the beau

5条回答
  •  猫巷女王i
    2021-02-19 06:28

    However, Scala's List is immutable (at least by default). What is the benefit of having an immutable linked list

    I'm a little late to the party here, but I felt there's an important point no one's made:

    On top of what Rex Kerr said, it's worth pointing out that building a new list by prepending to an immutable singly linked list is a constant time operation. You just create a new node that points to the already existing list. Since the list is immutable you know the new tail won't ever change, and you don't need to copy any data.

    The fact that you can build new, larger, but still immutable lists with a constant time operation, and with a small memory footprint(just the cost of one node) is, I suspect, a large part of the reason the data structure was chosen.

提交回复
热议问题