PageRenderTime 50ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/src/library/scala/collection/immutable/List.scala

http://github.com/scala/scala
Scala | 659 lines | 460 code | 63 blank | 136 comment | 112 complexity | 703115e039c8b3f4e6249a45129616f4 MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause, MIT
  1. /*
  2. * Scala (https://www.scala-lang.org)
  3. *
  4. * Copyright EPFL and Lightbend, Inc.
  5. *
  6. * Licensed under Apache License 2.0
  7. * (http://www.apache.org/licenses/LICENSE-2.0).
  8. *
  9. * See the NOTICE file distributed with this work for
  10. * additional information regarding copyright ownership.
  11. */
  12. package scala
  13. package collection
  14. package immutable
  15. import scala.annotation.unchecked.uncheckedVariance
  16. import scala.annotation.tailrec
  17. import mutable.{Builder, ListBuffer}
  18. import scala.collection.generic.DefaultSerializable
  19. import scala.runtime.Statics.releaseFence
  20. /** A class for immutable linked lists representing ordered collections
  21. * of elements of type `A`.
  22. *
  23. * This class comes with two implementing case classes `scala.Nil`
  24. * and `scala.::` that implement the abstract members `isEmpty`,
  25. * `head` and `tail`.
  26. *
  27. * This class is optimal for last-in-first-out (LIFO), stack-like access patterns. If you need another access
  28. * pattern, for example, random access or FIFO, consider using a collection more suited to this than `List`.
  29. *
  30. * ==Performance==
  31. * '''Time:''' `List` has `O(1)` prepend and head/tail access. Most other operations are `O(n)` on the number of elements in the list.
  32. * This includes the index-based lookup of elements, `length`, `append` and `reverse`.
  33. *
  34. * '''Space:''' `List` implements '''structural sharing''' of the tail list. This means that many operations are either
  35. * zero- or constant-memory cost.
  36. * {{{
  37. * val mainList = List(3, 2, 1)
  38. * val with4 = 4 :: mainList // re-uses mainList, costs one :: instance
  39. * val with42 = 42 :: mainList // also re-uses mainList, cost one :: instance
  40. * val shorter = mainList.tail // costs nothing as it uses the same 2::1::Nil instances as mainList
  41. * }}}
  42. *
  43. * @example {{{
  44. * // Make a list via the companion object factory
  45. * val days = List("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
  46. *
  47. * // Make a list element-by-element
  48. * val when = "AM" :: "PM" :: Nil
  49. *
  50. * // Pattern match
  51. * days match {
  52. * case firstDay :: otherDays =>
  53. * println("The first day of the week is: " + firstDay)
  54. * case Nil =>
  55. * println("There don't seem to be any week days.")
  56. * }
  57. * }}}
  58. *
  59. * @note The functional list is characterized by persistence and structural sharing, thus offering considerable
  60. * performance and space consumption benefits in some scenarios if used correctly.
  61. * However, note that objects having multiple references into the same functional list (that is,
  62. * objects that rely on structural sharing), will be serialized and deserialized with multiple lists, one for
  63. * each reference to it. I.e. structural sharing is lost after serialization/deserialization.
  64. *
  65. * @see [[http://docs.scala-lang.org/overviews/collections/concrete-immutable-collection-classes.html#lists "Scala's Collection Library overview"]]
  66. * section on `Lists` for more information.
  67. *
  68. * @define coll list
  69. * @define Coll `List`
  70. * @define orderDependent
  71. * @define orderDependentFold
  72. * @define mayNotTerminateInf
  73. * @define willNotTerminateInf
  74. */
  75. @SerialVersionUID(3L)
  76. sealed abstract class List[+A]
  77. extends AbstractSeq[A]
  78. with LinearSeq[A]
  79. with LinearSeqOps[A, List, List[A]]
  80. with StrictOptimizedLinearSeqOps[A, List, List[A]]
  81. with StrictOptimizedSeqOps[A, List, List[A]]
  82. with IterableFactoryDefaults[A, List]
  83. with DefaultSerializable {
  84. override def iterableFactory: SeqFactory[List] = List
  85. /** Adds an element at the beginning of this list.
  86. * @param elem the element to prepend.
  87. * @return a list which contains `x` as first element and
  88. * which continues with this list.
  89. * Example:
  90. * {{{1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3)}}}
  91. */
  92. def :: [B >: A](elem: B): List[B] = new ::(elem, this)
  93. /** Adds the elements of a given list in front of this list.
  94. *
  95. * Example:
  96. * {{{List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)}}}
  97. *
  98. * @param prefix The list elements to prepend.
  99. * @return a list resulting from the concatenation of the given
  100. * list `prefix` and this list.
  101. */
  102. def ::: [B >: A](prefix: List[B]): List[B] =
  103. if (isEmpty) prefix
  104. else if (prefix.isEmpty) this
  105. else {
  106. val result = new ::[B](prefix.head, this)
  107. var curr = result
  108. var that = prefix.tail
  109. while (!that.isEmpty) {
  110. val temp = new ::[B](that.head, this)
  111. curr.next = temp
  112. curr = temp
  113. that = that.tail
  114. }
  115. releaseFence()
  116. result
  117. }
  118. /** Adds the elements of a given list in reverse order in front of this list.
  119. * `xs reverse_::: ys` is equivalent to
  120. * `xs.reverse ::: ys` but is more efficient.
  121. *
  122. * @param prefix the prefix to reverse and then prepend
  123. * @return the concatenation of the reversed prefix and the current list.
  124. */
  125. def reverse_:::[B >: A](prefix: List[B]): List[B] = {
  126. var these: List[B] = this
  127. var pres = prefix
  128. while (!pres.isEmpty) {
  129. these = pres.head :: these
  130. pres = pres.tail
  131. }
  132. these
  133. }
  134. override final def isEmpty: Boolean = this eq Nil
  135. override def prepended[B >: A](elem: B): List[B] = elem :: this
  136. override def prependedAll[B >: A](prefix: collection.IterableOnce[B]): List[B] = prefix match {
  137. case xs: List[B] => xs ::: this
  138. case _ if prefix.knownSize == 0 => this
  139. case b: ListBuffer[B] if this.isEmpty => b.toList
  140. case _ =>
  141. val iter = prefix.iterator
  142. if (iter.hasNext) {
  143. val result = new ::[B](iter.next(), this)
  144. var curr = result
  145. while (iter.hasNext) {
  146. val temp = new ::[B](iter.next(), this)
  147. curr.next = temp
  148. curr = temp
  149. }
  150. releaseFence()
  151. result
  152. } else {
  153. this
  154. }
  155. }
  156. // When calling appendAll with another list `suffix`, avoid copying `suffix`
  157. override def appendedAll[B >: A](suffix: collection.IterableOnce[B]): List[B] = suffix match {
  158. case xs: List[B] => this ::: xs
  159. case _ => super.appendedAll(suffix)
  160. }
  161. override def take(n: Int): List[A] = if (isEmpty || n <= 0) Nil else {
  162. val h = new ::(head, Nil)
  163. var t = h
  164. var rest = tail
  165. var i = 1
  166. while ({if (rest.isEmpty) return this; i < n}) {
  167. i += 1
  168. val nx = new ::(rest.head, Nil)
  169. t.next = nx
  170. t = nx
  171. rest = rest.tail
  172. }
  173. releaseFence()
  174. h
  175. }
  176. /**
  177. * @example {{{
  178. * // Given a list
  179. * val letters = List('a','b','c','d','e')
  180. *
  181. * // `slice` returns all elements beginning at index `from` and afterwards,
  182. * // up until index `until` (excluding index `until`.)
  183. * letters.slice(1,3) // Returns List('b','c')
  184. * }}}
  185. */
  186. override def slice(from: Int, until: Int): List[A] = {
  187. val lo = scala.math.max(from, 0)
  188. if (until <= lo || isEmpty) Nil
  189. else this drop lo take (until - lo)
  190. }
  191. override def takeRight(n: Int): List[A] = {
  192. @tailrec
  193. def loop(lead: List[A], lag: List[A]): List[A] = lead match {
  194. case Nil => lag
  195. case _ :: tail => loop(tail, lag.tail)
  196. }
  197. loop(drop(n), this)
  198. }
  199. // dropRight is inherited from LinearSeq
  200. override def splitAt(n: Int): (List[A], List[A]) = {
  201. val b = new ListBuffer[A]
  202. var i = 0
  203. var these = this
  204. while (!these.isEmpty && i < n) {
  205. i += 1
  206. b += these.head
  207. these = these.tail
  208. }
  209. (b.toList, these)
  210. }
  211. override def updated[B >: A](index: Int, elem: B): List[B] = {
  212. var i = 0
  213. var current = this
  214. val prefix = ListBuffer.empty[B]
  215. while (i < index && current.nonEmpty) {
  216. i += 1
  217. prefix += current.head
  218. current = current.tail
  219. }
  220. if (i == index && current.nonEmpty) {
  221. prefix.prependToList(elem :: current.tail)
  222. } else {
  223. throw new IndexOutOfBoundsException(s"$index is out of bounds (min 0, max ${length-1})")
  224. }
  225. }
  226. final override def map[B](f: A => B): List[B] = {
  227. if (this eq Nil) Nil else {
  228. val h = new ::[B](f(head), Nil)
  229. var t: ::[B] = h
  230. var rest = tail
  231. while (rest ne Nil) {
  232. val nx = new ::(f(rest.head), Nil)
  233. t.next = nx
  234. t = nx
  235. rest = rest.tail
  236. }
  237. releaseFence()
  238. h
  239. }
  240. }
  241. final override def collect[B](pf: PartialFunction[A, B]): List[B] = {
  242. if (this eq Nil) Nil else {
  243. var rest = this
  244. var h: ::[B] = null
  245. var x: Any = null
  246. // Special case for first element
  247. while (h eq null) {
  248. x = pf.applyOrElse(rest.head, List.partialNotApplied)
  249. if (x.asInstanceOf[AnyRef] ne List.partialNotApplied) h = new ::(x.asInstanceOf[B], Nil)
  250. rest = rest.tail
  251. if (rest eq Nil) return if (h eq null) Nil else h
  252. }
  253. var t = h
  254. // Remaining elements
  255. while (rest ne Nil) {
  256. x = pf.applyOrElse(rest.head, List.partialNotApplied)
  257. if (x.asInstanceOf[AnyRef] ne List.partialNotApplied) {
  258. val nx = new ::(x.asInstanceOf[B], Nil)
  259. t.next = nx
  260. t = nx
  261. }
  262. rest = rest.tail
  263. }
  264. releaseFence()
  265. h
  266. }
  267. }
  268. final override def flatMap[B](f: A => IterableOnce[B]): List[B] = {
  269. var rest = this
  270. var h: ::[B] = null
  271. var t: ::[B] = null
  272. while (rest ne Nil) {
  273. val it = f(rest.head).iterator
  274. while (it.hasNext) {
  275. val nx = new ::(it.next(), Nil)
  276. if (t eq null) {
  277. h = nx
  278. } else {
  279. t.next = nx
  280. }
  281. t = nx
  282. }
  283. rest = rest.tail
  284. }
  285. if (h eq null) Nil else {releaseFence(); h}
  286. }
  287. @inline final override def takeWhile(p: A => Boolean): List[A] = {
  288. val b = new ListBuffer[A]
  289. var these = this
  290. while (!these.isEmpty && p(these.head)) {
  291. b += these.head
  292. these = these.tail
  293. }
  294. b.toList
  295. }
  296. @inline final override def span(p: A => Boolean): (List[A], List[A]) = {
  297. val b = new ListBuffer[A]
  298. var these = this
  299. while (!these.isEmpty && p(these.head)) {
  300. b += these.head
  301. these = these.tail
  302. }
  303. (b.toList, these)
  304. }
  305. // Overridden with an implementation identical to the inherited one (at this time)
  306. // solely so it can be finalized and thus inlinable.
  307. @inline final override def foreach[U](f: A => U): Unit = {
  308. var these = this
  309. while (!these.isEmpty) {
  310. f(these.head)
  311. these = these.tail
  312. }
  313. }
  314. final override def reverse: List[A] = {
  315. var result: List[A] = Nil
  316. var these = this
  317. while (!these.isEmpty) {
  318. result = these.head :: result
  319. these = these.tail
  320. }
  321. result
  322. }
  323. final override def foldRight[B](z: B)(op: (A, B) => B): B = {
  324. var acc = z
  325. var these: List[A] = reverse
  326. while (!these.isEmpty) {
  327. acc = op(these.head, acc)
  328. these = these.tail
  329. }
  330. acc
  331. }
  332. // Copy/Paste overrides to avoid interface calls inside loops.
  333. override final def length: Int = {
  334. var these = this
  335. var len = 0
  336. while (!these.isEmpty) {
  337. len += 1
  338. these = these.tail
  339. }
  340. len
  341. }
  342. override final def lengthCompare(len: Int): Int = {
  343. @tailrec def loop(i: Int, xs: List[A]): Int = {
  344. if (i == len)
  345. if (xs.isEmpty) 0 else 1
  346. else if (xs.isEmpty)
  347. -1
  348. else
  349. loop(i + 1, xs.tail)
  350. }
  351. if (len < 0) 1
  352. else loop(0, coll)
  353. }
  354. override final def forall(p: A => Boolean): Boolean = {
  355. var these: List[A] = this
  356. while (!these.isEmpty) {
  357. if (!p(these.head)) return false
  358. these = these.tail
  359. }
  360. true
  361. }
  362. override final def exists(p: A => Boolean): Boolean = {
  363. var these: List[A] = this
  364. while (!these.isEmpty) {
  365. if (p(these.head)) return true
  366. these = these.tail
  367. }
  368. false
  369. }
  370. override final def contains[A1 >: A](elem: A1): Boolean = {
  371. var these: List[A] = this
  372. while (!these.isEmpty) {
  373. if (these.head == elem) return true
  374. these = these.tail
  375. }
  376. false
  377. }
  378. override final def find(p: A => Boolean): Option[A] = {
  379. var these: List[A] = this
  380. while (!these.isEmpty) {
  381. if (p(these.head)) return Some(these.head)
  382. these = these.tail
  383. }
  384. None
  385. }
  386. override def last: A = {
  387. if (isEmpty) throw new NoSuchElementException("List.last")
  388. else {
  389. var these = this
  390. var scout = tail
  391. while (!scout.isEmpty) {
  392. these = scout
  393. scout = scout.tail
  394. }
  395. these.head
  396. }
  397. }
  398. override def corresponds[B](that: collection.Seq[B])(p: (A, B) => Boolean): Boolean = that match {
  399. case that: LinearSeq[B] =>
  400. var i = this
  401. var j = that
  402. while (!(i.isEmpty || j.isEmpty)) {
  403. if (!p(i.head, j.head))
  404. return false
  405. i = i.tail
  406. j = j.tail
  407. }
  408. i.isEmpty && j.isEmpty
  409. case _ =>
  410. super.corresponds(that)(p)
  411. }
  412. override protected[this] def className = "List"
  413. /** Builds a new list by applying a function to all elements of this list.
  414. * Like `xs map f`, but returns `xs` unchanged if function
  415. * `f` maps all elements to themselves (as determined by `eq`).
  416. *
  417. * @param f the function to apply to each element.
  418. * @tparam B the element type of the returned collection.
  419. * @return a list resulting from applying the given function
  420. * `f` to each element of this list and collecting the results.
  421. */
  422. @`inline` final def mapConserve[B >: A <: AnyRef](f: A => B): List[B] = {
  423. // Note to developers: there exists a duplication between this function and `reflect.internal.util.Collections#map2Conserve`.
  424. // If any successful optimization attempts or other changes are made, please rehash them there too.
  425. @tailrec
  426. def loop(mappedHead: List[B], mappedLast: ::[B], unchanged: List[A], pending: List[A]): List[B] = {
  427. if (pending.isEmpty) {
  428. if (mappedHead eq null) unchanged
  429. else {
  430. mappedLast.next = (unchanged: List[B])
  431. mappedHead
  432. }
  433. }
  434. else {
  435. val head0 = pending.head
  436. val head1 = f(head0)
  437. if (head1 eq head0.asInstanceOf[AnyRef])
  438. loop(mappedHead, mappedLast, unchanged, pending.tail)
  439. else {
  440. var xc = unchanged
  441. var mappedHead1: List[B] = mappedHead
  442. var mappedLast1: ::[B] = mappedLast
  443. while (xc ne pending) {
  444. val next = new ::[B](xc.head, Nil)
  445. if (mappedHead1 eq null) mappedHead1 = next
  446. if (mappedLast1 ne null) mappedLast1.next = next
  447. mappedLast1 = next
  448. xc = xc.tail
  449. }
  450. val next = new ::(head1, Nil)
  451. if (mappedHead1 eq null) mappedHead1 = next
  452. if (mappedLast1 ne null) mappedLast1.next = next
  453. mappedLast1 = next
  454. val tail0 = pending.tail
  455. loop(mappedHead1, mappedLast1, tail0, tail0)
  456. }
  457. }
  458. }
  459. val result = loop(null, null, this, this)
  460. releaseFence()
  461. result
  462. }
  463. override def filter(p: A => Boolean): List[A] = filterCommon(p, isFlipped = false)
  464. override def filterNot(p: A => Boolean): List[A] = filterCommon(p, isFlipped = true)
  465. private[this] def filterCommon(p: A => Boolean, isFlipped: Boolean): List[A] = {
  466. // everything seen so far so far is not included
  467. @tailrec def noneIn(l: List[A]): List[A] = {
  468. if (l.isEmpty)
  469. Nil
  470. else {
  471. val h = l.head
  472. val t = l.tail
  473. if (p(h) != isFlipped)
  474. allIn(l, t)
  475. else
  476. noneIn(t)
  477. }
  478. }
  479. // everything from 'start' is included, if everything from this point is in we can return the origin
  480. // start otherwise if we discover an element that is out we must create a new partial list.
  481. @tailrec def allIn(start: List[A], remaining: List[A]): List[A] = {
  482. if (remaining.isEmpty)
  483. start
  484. else {
  485. val x = remaining.head
  486. if (p(x) != isFlipped)
  487. allIn(start, remaining.tail)
  488. else
  489. partialFill(start, remaining)
  490. }
  491. }
  492. // we have seen elements that should be included then one that should be excluded, start building
  493. def partialFill(origStart: List[A], firstMiss: List[A]): List[A] = {
  494. val newHead = new ::(origStart.head, Nil)
  495. var toProcess = origStart.tail
  496. var currentLast = newHead
  497. // we know that all elements are :: until at least firstMiss.tail
  498. while (!(toProcess eq firstMiss)) {
  499. val newElem = new ::(toProcess.head, Nil)
  500. currentLast.next = newElem
  501. currentLast = newElem
  502. toProcess = toProcess.tail
  503. }
  504. // at this point newHead points to a list which is a duplicate of all the 'in' elements up to the first miss.
  505. // currentLast is the last element in that list.
  506. // now we are going to try and share as much of the tail as we can, only moving elements across when we have to.
  507. var next = firstMiss.tail
  508. var nextToCopy = next // the next element we would need to copy to our list if we cant share.
  509. while (!next.isEmpty) {
  510. // generally recommended is next.isNonEmpty but this incurs an extra method call.
  511. val head: A = next.head
  512. if (p(head) != isFlipped) {
  513. next = next.tail
  514. } else {
  515. // its not a match - do we have outstanding elements?
  516. while (!(nextToCopy eq next)) {
  517. val newElem = new ::(nextToCopy.head, Nil)
  518. currentLast.next = newElem
  519. currentLast = newElem
  520. nextToCopy = nextToCopy.tail
  521. }
  522. nextToCopy = next.tail
  523. next = next.tail
  524. }
  525. }
  526. // we have remaining elements - they are unchanged attach them to the end
  527. if (!nextToCopy.isEmpty)
  528. currentLast.next = nextToCopy
  529. newHead
  530. }
  531. val result = noneIn(this)
  532. releaseFence()
  533. result
  534. }
  535. override def partition(p: A => Boolean): (List[A], List[A]) = {
  536. if (isEmpty) List.TupleOfNil
  537. else super.partition(p) match {
  538. case (Nil, xs) => (Nil, this)
  539. case (xs, Nil) => (this, Nil)
  540. case pair => pair
  541. }
  542. }
  543. final override def toList: List[A] = this
  544. // Override for performance
  545. override def equals(o: scala.Any): Boolean = {
  546. @tailrec def listEq(a: List[_], b: List[_]): Boolean =
  547. (a eq b) || {
  548. val aEmpty = a.isEmpty
  549. val bEmpty = b.isEmpty
  550. if (!(aEmpty || bEmpty) && a.head == b.head) {
  551. listEq(a.tail, b.tail)
  552. }
  553. else {
  554. aEmpty && bEmpty
  555. }
  556. }
  557. o match {
  558. case that: List[_] => listEq(this, that)
  559. case _ => super.equals(o)
  560. }
  561. }
  562. }
  563. // Internal code that mutates `next` _must_ call `Statics.releaseFence()` if either immediately, or
  564. // before a newly-allocated, thread-local :: instance is aliased (e.g. in ListBuffer.toList)
  565. final case class :: [+A](override val head: A, private[scala] var next: List[A @uncheckedVariance]) // sound because `next` is used only locally
  566. extends List[A] {
  567. releaseFence()
  568. override def headOption: Some[A] = Some(head)
  569. override def tail: List[A] = next
  570. }
  571. case object Nil extends List[Nothing] {
  572. override def head: Nothing = throw new NoSuchElementException("head of empty list")
  573. override def headOption: None.type = None
  574. override def tail: Nothing = throw new UnsupportedOperationException("tail of empty list")
  575. override def last: Nothing = throw new NoSuchElementException("last of empty list")
  576. override def init: Nothing = throw new UnsupportedOperationException("init of empty list")
  577. override def knownSize: Int = 0
  578. override def iterator: Iterator[Nothing] = Iterator.empty
  579. override def unzip[A1, A2](implicit asPair: Nothing => (A1, A2)): (List[A1], List[A2]) = EmptyUnzip
  580. @transient
  581. private[this] val EmptyUnzip = (Nil, Nil)
  582. }
  583. /**
  584. * $factoryInfo
  585. * @define coll list
  586. * @define Coll `List`
  587. */
  588. @SerialVersionUID(3L)
  589. object List extends StrictOptimizedSeqFactory[List] {
  590. private val TupleOfNil = (Nil, Nil)
  591. def from[B](coll: collection.IterableOnce[B]): List[B] = Nil.prependedAll(coll)
  592. def newBuilder[A]: Builder[A, List[A]] = new ListBuffer()
  593. def empty[A]: List[A] = Nil
  594. @transient
  595. private[collection] val partialNotApplied = new Function1[Any, Any] { def apply(x: Any): Any = this }
  596. }