Why no immutable double linked list in Scala collections?

后端 未结 5 720
轻奢々
轻奢々 2021-02-05 16:33

Looking at this question, where the questioner is interested in the first and last instances of some element in a List, it seems a more efficient solution would be

5条回答
  •  醉酒成梦
    2021-02-05 17:13

    There are many impediments to such a structure, but one is very pressing: a doubly linked list cannot be persistent.

    The logic behind this is pretty simple: from any node on the list, you can reach any other node. So, if I added an element X to this list DL, and tried to use a part of DL, I'd face this contradiction: from the node pointing to X one can reach every element in part(DL), but, by the properties of the doubly linked list, that means from any element of part(DL) I can reach the node pointing to X. Since part(DL) is supposed to be immutable and part of DL, and since DL did not include the node pointing to X, that just cannot be.

    Non-persistent immutable data structures might have some uses, but they are generally bad for most operations, since they need to be recreated whenever a derivative is produced.

    Now, there's the minor matter of creating mutually referencing strict objects, but this is surmountable. One can use by-name parameters and lazy vals, or one can do like Scala's List: actually create a mutable collection, and then "freeze" it in immutable state (see ListBuffer and it's toList method).

提交回复
热议问题