Why is appending to a list bad?

前端 未结 5 1251
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  Happy的楠姐
    2020-12-01 01:53

    Since the question was just updated, it's worth noting that things have changed here.

    In today's Scala, you can simply use xs :+ x to append an item at the end of any sequential collection. (There is also x +: xs to prepend. The mnemonic for many of Scala's 2.8+ collection operations is that the colon goes next to the collection.)

    This will be O(n) with the default linked implementation of List or Seq, but if you use Vector or IndexedSeq, this will be effectively constant time. Scala's Vector is probably Scala's most useful list-like collection—unlike Java's Vector which is mostly useless these days.

    If you are working in Scala 2.8 or higher, the collections introduction is an absolute must read.

提交回复
热议问题