国内流行的内容管理系统(CMS)多端全媒体解决方案 https://www.dedebiz.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

768 lines
28KB

  1. <!doctype html>
  2. <title>CodeMirror: Scala mode</title>
  3. <meta charset="utf-8"/>
  4. <link rel=stylesheet href="../../doc/docs.css">
  5. <link rel="stylesheet" href="../../lib/codemirror.css">
  6. <link rel="stylesheet" href="../../theme/ambiance.css">
  7. <script src="../../lib/codemirror.js"></script>
  8. <script src="../../addon/edit/matchbrackets.js"></script>
  9. <script src="clike.js"></script>
  10. <div id=nav>
  11. <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a>
  12. <ul>
  13. <li><a href="../../index.html">Home</a>
  14. <li><a href="../../doc/manual.html">Manual</a>
  15. <li><a href="https://github.com/codemirror/codemirror">Code</a>
  16. </ul>
  17. <ul>
  18. <li><a href="../index.html">Language modes</a>
  19. <li><a class=active href="#">Scala</a>
  20. </ul>
  21. </div>
  22. <article>
  23. <h2>Scala mode</h2>
  24. <form>
  25. <textarea id="code" name="code">
  26. /* __ *\
  27. ** ________ ___ / / ___ Scala API **
  28. ** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL **
  29. ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
  30. ** /____/\___/_/ |_/____/_/ | | **
  31. ** |/ **
  32. \* */
  33. package scala.collection
  34. import generic._
  35. import mutable.{ Builder, ListBuffer }
  36. import annotation.{tailrec, migration, bridge}
  37. import annotation.unchecked.{ uncheckedVariance => uV }
  38. import parallel.ParIterable
  39. /** A template trait for traversable collections of type `Traversable[A]`.
  40. *
  41. * $traversableInfo
  42. * @define mutability
  43. * @define traversableInfo
  44. * This is a base trait of all kinds of $mutability Scala collections. It
  45. * implements the behavior common to all collections, in terms of a method
  46. * `foreach` with signature:
  47. * {{{
  48. * def foreach[U](f: Elem => U): Unit
  49. * }}}
  50. * Collection classes mixing in this trait provide a concrete
  51. * `foreach` method which traverses all the
  52. * elements contained in the collection, applying a given function to each.
  53. * They also need to provide a method `newBuilder`
  54. * which creates a builder for collections of the same kind.
  55. *
  56. * A traversable class might or might not have two properties: strictness
  57. * and orderedness. Neither is represented as a type.
  58. *
  59. * The instances of a strict collection class have all their elements
  60. * computed before they can be used as values. By contrast, instances of
  61. * a non-strict collection class may defer computation of some of their
  62. * elements until after the instance is available as a value.
  63. * A typical example of a non-strict collection class is a
  64. * <a href="../immutable/Stream.html" target="ContentFrame">
  65. * `scala.collection.immutable.Stream`</a>.
  66. * A more general class of examples are `TraversableViews`.
  67. *
  68. * If a collection is an instance of an ordered collection class, traversing
  69. * its elements with `foreach` will always visit elements in the
  70. * same order, even for different runs of the program. If the class is not
  71. * ordered, `foreach` can visit elements in different orders for
  72. * different runs (but it will keep the same order in the same run).'
  73. *
  74. * A typical example of a collection class which is not ordered is a
  75. * `HashMap` of objects. The traversal order for hash maps will
  76. * depend on the hash codes of its elements, and these hash codes might
  77. * differ from one run to the next. By contrast, a `LinkedHashMap`
  78. * is ordered because it's `foreach` method visits elements in the
  79. * order they were inserted into the `HashMap`.
  80. *
  81. * @author Martin Odersky
  82. * @version 2.8
  83. * @since 2.8
  84. * @tparam A the element type of the collection
  85. * @tparam Repr the type of the actual collection containing the elements.
  86. *
  87. * @define Coll Traversable
  88. * @define coll traversable collection
  89. */
  90. trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr]
  91. with FilterMonadic[A, Repr]
  92. with TraversableOnce[A]
  93. with GenTraversableLike[A, Repr]
  94. with Parallelizable[A, ParIterable[A]]
  95. {
  96. self =>
  97. import Traversable.breaks._
  98. /** The type implementing this traversable */
  99. protected type Self = Repr
  100. /** The collection of type $coll underlying this `TraversableLike` object.
  101. * By default this is implemented as the `TraversableLike` object itself,
  102. * but this can be overridden.
  103. */
  104. def repr: Repr = this.asInstanceOf[Repr]
  105. /** The underlying collection seen as an instance of `$Coll`.
  106. * By default this is implemented as the current collection object itself,
  107. * but this can be overridden.
  108. */
  109. protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]]
  110. /** A conversion from collections of type `Repr` to `$Coll` objects.
  111. * By default this is implemented as just a cast, but this can be overridden.
  112. */
  113. protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]]
  114. /** Creates a new builder for this collection type.
  115. */
  116. protected[this] def newBuilder: Builder[A, Repr]
  117. protected[this] def parCombiner = ParIterable.newCombiner[A]
  118. /** Applies a function `f` to all elements of this $coll.
  119. *
  120. * Note: this method underlies the implementation of most other bulk operations.
  121. * It's important to implement this method in an efficient way.
  122. *
  123. *
  124. * @param f the function that is applied for its side-effect to every element.
  125. * The result of function `f` is discarded.
  126. *
  127. * @tparam U the type parameter describing the result of function `f`.
  128. * This result will always be ignored. Typically `U` is `Unit`,
  129. * but this is not necessary.
  130. *
  131. * @usecase def foreach(f: A => Unit): Unit
  132. */
  133. def foreach[U](f: A => U): Unit
  134. /** Tests whether this $coll is empty.
  135. *
  136. * @return `true` if the $coll contain no elements, `false` otherwise.
  137. */
  138. def isEmpty: Boolean = {
  139. var result = true
  140. breakable {
  141. for (x <- this) {
  142. result = false
  143. break
  144. }
  145. }
  146. result
  147. }
  148. /** Tests whether this $coll is known to have a finite size.
  149. * All strict collections are known to have finite size. For a non-strict collection
  150. * such as `Stream`, the predicate returns `true` if all elements have been computed.
  151. * It returns `false` if the stream is not yet evaluated to the end.
  152. *
  153. * Note: many collection methods will not work on collections of infinite sizes.
  154. *
  155. * @return `true` if this collection is known to have finite size, `false` otherwise.
  156. */
  157. def hasDefiniteSize = true
  158. def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  159. val b = bf(repr)
  160. if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.seq.size)
  161. b ++= thisCollection
  162. b ++= that.seq
  163. b.result
  164. }
  165. @bridge
  166. def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
  167. ++(that: GenTraversableOnce[B])(bf)
  168. /** Concatenates this $coll with the elements of a traversable collection.
  169. * It differs from ++ in that the right operand determines the type of the
  170. * resulting collection rather than the left one.
  171. *
  172. * @param that the traversable to append.
  173. * @tparam B the element type of the returned collection.
  174. * @tparam That $thatinfo
  175. * @param bf $bfinfo
  176. * @return a new collection of type `That` which contains all elements
  177. * of this $coll followed by all elements of `that`.
  178. *
  179. * @usecase def ++:[B](that: TraversableOnce[B]): $Coll[B]
  180. *
  181. * @return a new $coll which contains all elements of this $coll
  182. * followed by all elements of `that`.
  183. */
  184. def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  185. val b = bf(repr)
  186. if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size)
  187. b ++= that
  188. b ++= thisCollection
  189. b.result
  190. }
  191. /** This overload exists because: for the implementation of ++: we should reuse
  192. * that of ++ because many collections override it with more efficient versions.
  193. * Since TraversableOnce has no '++' method, we have to implement that directly,
  194. * but Traversable and down can use the overload.
  195. */
  196. def ++:[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
  197. (that ++ seq)(breakOut)
  198. def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  199. val b = bf(repr)
  200. b.sizeHint(this)
  201. for (x <- this) b += f(x)
  202. b.result
  203. }
  204. def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  205. val b = bf(repr)
  206. for (x <- this) b ++= f(x).seq
  207. b.result
  208. }
  209. /** Selects all elements of this $coll which satisfy a predicate.
  210. *
  211. * @param p the predicate used to test elements.
  212. * @return a new $coll consisting of all elements of this $coll that satisfy the given
  213. * predicate `p`. The order of the elements is preserved.
  214. */
  215. def filter(p: A => Boolean): Repr = {
  216. val b = newBuilder
  217. for (x <- this)
  218. if (p(x)) b += x
  219. b.result
  220. }
  221. /** Selects all elements of this $coll which do not satisfy a predicate.
  222. *
  223. * @param p the predicate used to test elements.
  224. * @return a new $coll consisting of all elements of this $coll that do not satisfy the given
  225. * predicate `p`. The order of the elements is preserved.
  226. */
  227. def filterNot(p: A => Boolean): Repr = filter(!p(_))
  228. def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  229. val b = bf(repr)
  230. for (x <- this) if (pf.isDefinedAt(x)) b += pf(x)
  231. b.result
  232. }
  233. /** Builds a new collection by applying an option-valued function to all
  234. * elements of this $coll on which the function is defined.
  235. *
  236. * @param f the option-valued function which filters and maps the $coll.
  237. * @tparam B the element type of the returned collection.
  238. * @tparam That $thatinfo
  239. * @param bf $bfinfo
  240. * @return a new collection of type `That` resulting from applying the option-valued function
  241. * `f` to each element and collecting all defined results.
  242. * The order of the elements is preserved.
  243. *
  244. * @usecase def filterMap[B](f: A => Option[B]): $Coll[B]
  245. *
  246. * @param pf the partial function which filters and maps the $coll.
  247. * @return a new $coll resulting from applying the given option-valued function
  248. * `f` to each element and collecting all defined results.
  249. * The order of the elements is preserved.
  250. def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  251. val b = bf(repr)
  252. for (x <- this)
  253. f(x) match {
  254. case Some(y) => b += y
  255. case _ =>
  256. }
  257. b.result
  258. }
  259. */
  260. /** Partitions this $coll in two ${coll}s according to a predicate.
  261. *
  262. * @param p the predicate on which to partition.
  263. * @return a pair of ${coll}s: the first $coll consists of all elements that
  264. * satisfy the predicate `p` and the second $coll consists of all elements
  265. * that don't. The relative order of the elements in the resulting ${coll}s
  266. * is the same as in the original $coll.
  267. */
  268. def partition(p: A => Boolean): (Repr, Repr) = {
  269. val l, r = newBuilder
  270. for (x <- this) (if (p(x)) l else r) += x
  271. (l.result, r.result)
  272. }
  273. def groupBy[K](f: A => K): immutable.Map[K, Repr] = {
  274. val m = mutable.Map.empty[K, Builder[A, Repr]]
  275. for (elem <- this) {
  276. val key = f(elem)
  277. val bldr = m.getOrElseUpdate(key, newBuilder)
  278. bldr += elem
  279. }
  280. val b = immutable.Map.newBuilder[K, Repr]
  281. for ((k, v) <- m)
  282. b += ((k, v.result))
  283. b.result
  284. }
  285. /** Tests whether a predicate holds for all elements of this $coll.
  286. *
  287. * $mayNotTerminateInf
  288. *
  289. * @param p the predicate used to test elements.
  290. * @return `true` if the given predicate `p` holds for all elements
  291. * of this $coll, otherwise `false`.
  292. */
  293. def forall(p: A => Boolean): Boolean = {
  294. var result = true
  295. breakable {
  296. for (x <- this)
  297. if (!p(x)) { result = false; break }
  298. }
  299. result
  300. }
  301. /** Tests whether a predicate holds for some of the elements of this $coll.
  302. *
  303. * $mayNotTerminateInf
  304. *
  305. * @param p the predicate used to test elements.
  306. * @return `true` if the given predicate `p` holds for some of the
  307. * elements of this $coll, otherwise `false`.
  308. */
  309. def exists(p: A => Boolean): Boolean = {
  310. var result = false
  311. breakable {
  312. for (x <- this)
  313. if (p(x)) { result = true; break }
  314. }
  315. result
  316. }
  317. /** Finds the first element of the $coll satisfying a predicate, if any.
  318. *
  319. * $mayNotTerminateInf
  320. * $orderDependent
  321. *
  322. * @param p the predicate used to test elements.
  323. * @return an option value containing the first element in the $coll
  324. * that satisfies `p`, or `None` if none exists.
  325. */
  326. def find(p: A => Boolean): Option[A] = {
  327. var result: Option[A] = None
  328. breakable {
  329. for (x <- this)
  330. if (p(x)) { result = Some(x); break }
  331. }
  332. result
  333. }
  334. def scan[B >: A, That](z: B)(op: (B, B) => B)(implicit cbf: CanBuildFrom[Repr, B, That]): That = scanLeft(z)(op)
  335. def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  336. val b = bf(repr)
  337. b.sizeHint(this, 1)
  338. var acc = z
  339. b += acc
  340. for (x <- this) { acc = op(acc, x); b += acc }
  341. b.result
  342. }
  343. @migration(2, 9,
  344. "This scanRight definition has changed in 2.9.\n" +
  345. "The previous behavior can be reproduced with scanRight.reverse."
  346. )
  347. def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  348. var scanned = List(z)
  349. var acc = z
  350. for (x <- reversed) {
  351. acc = op(x, acc)
  352. scanned ::= acc
  353. }
  354. val b = bf(repr)
  355. for (elem <- scanned) b += elem
  356. b.result
  357. }
  358. /** Selects the first element of this $coll.
  359. * $orderDependent
  360. * @return the first element of this $coll.
  361. * @throws `NoSuchElementException` if the $coll is empty.
  362. */
  363. def head: A = {
  364. var result: () => A = () => throw new NoSuchElementException
  365. breakable {
  366. for (x <- this) {
  367. result = () => x
  368. break
  369. }
  370. }
  371. result()
  372. }
  373. /** Optionally selects the first element.
  374. * $orderDependent
  375. * @return the first element of this $coll if it is nonempty, `None` if it is empty.
  376. */
  377. def headOption: Option[A] = if (isEmpty) None else Some(head)
  378. /** Selects all elements except the first.
  379. * $orderDependent
  380. * @return a $coll consisting of all elements of this $coll
  381. * except the first one.
  382. * @throws `UnsupportedOperationException` if the $coll is empty.
  383. */
  384. override def tail: Repr = {
  385. if (isEmpty) throw new UnsupportedOperationException("empty.tail")
  386. drop(1)
  387. }
  388. /** Selects the last element.
  389. * $orderDependent
  390. * @return The last element of this $coll.
  391. * @throws NoSuchElementException If the $coll is empty.
  392. */
  393. def last: A = {
  394. var lst = head
  395. for (x <- this)
  396. lst = x
  397. lst
  398. }
  399. /** Optionally selects the last element.
  400. * $orderDependent
  401. * @return the last element of this $coll$ if it is nonempty, `None` if it is empty.
  402. */
  403. def lastOption: Option[A] = if (isEmpty) None else Some(last)
  404. /** Selects all elements except the last.
  405. * $orderDependent
  406. * @return a $coll consisting of all elements of this $coll
  407. * except the last one.
  408. * @throws `UnsupportedOperationException` if the $coll is empty.
  409. */
  410. def init: Repr = {
  411. if (isEmpty) throw new UnsupportedOperationException("empty.init")
  412. var lst = head
  413. var follow = false
  414. val b = newBuilder
  415. b.sizeHint(this, -1)
  416. for (x <- this.seq) {
  417. if (follow) b += lst
  418. else follow = true
  419. lst = x
  420. }
  421. b.result
  422. }
  423. def take(n: Int): Repr = slice(0, n)
  424. def drop(n: Int): Repr =
  425. if (n <= 0) {
  426. val b = newBuilder
  427. b.sizeHint(this)
  428. b ++= thisCollection result
  429. }
  430. else sliceWithKnownDelta(n, Int.MaxValue, -n)
  431. def slice(from: Int, until: Int): Repr = sliceWithKnownBound(math.max(from, 0), until)
  432. // Precondition: from >= 0, until > 0, builder already configured for building.
  433. private[this] def sliceInternal(from: Int, until: Int, b: Builder[A, Repr]): Repr = {
  434. var i = 0
  435. breakable {
  436. for (x <- this.seq) {
  437. if (i >= from) b += x
  438. i += 1
  439. if (i >= until) break
  440. }
  441. }
  442. b.result
  443. }
  444. // Precondition: from >= 0
  445. private[scala] def sliceWithKnownDelta(from: Int, until: Int, delta: Int): Repr = {
  446. val b = newBuilder
  447. if (until <= from) b.result
  448. else {
  449. b.sizeHint(this, delta)
  450. sliceInternal(from, until, b)
  451. }
  452. }
  453. // Precondition: from >= 0
  454. private[scala] def sliceWithKnownBound(from: Int, until: Int): Repr = {
  455. val b = newBuilder
  456. if (until <= from) b.result
  457. else {
  458. b.sizeHintBounded(until - from, this)
  459. sliceInternal(from, until, b)
  460. }
  461. }
  462. def takeWhile(p: A => Boolean): Repr = {
  463. val b = newBuilder
  464. breakable {
  465. for (x <- this) {
  466. if (!p(x)) break
  467. b += x
  468. }
  469. }
  470. b.result
  471. }
  472. def dropWhile(p: A => Boolean): Repr = {
  473. val b = newBuilder
  474. var go = false
  475. for (x <- this) {
  476. if (!p(x)) go = true
  477. if (go) b += x
  478. }
  479. b.result
  480. }
  481. def span(p: A => Boolean): (Repr, Repr) = {
  482. val l, r = newBuilder
  483. var toLeft = true
  484. for (x <- this) {
  485. toLeft = toLeft && p(x)
  486. (if (toLeft) l else r) += x
  487. }
  488. (l.result, r.result)
  489. }
  490. def splitAt(n: Int): (Repr, Repr) = {
  491. val l, r = newBuilder
  492. l.sizeHintBounded(n, this)
  493. if (n >= 0) r.sizeHint(this, -n)
  494. var i = 0
  495. for (x <- this) {
  496. (if (i < n) l else r) += x
  497. i += 1
  498. }
  499. (l.result, r.result)
  500. }
  501. /** Iterates over the tails of this $coll. The first value will be this
  502. * $coll and the final one will be an empty $coll, with the intervening
  503. * values the results of successive applications of `tail`.
  504. *
  505. * @return an iterator over all the tails of this $coll
  506. * @example `List(1,2,3).tails = Iterator(List(1,2,3), List(2,3), List(3), Nil)`
  507. */
  508. def tails: Iterator[Repr] = iterateUntilEmpty(_.tail)
  509. /** Iterates over the inits of this $coll. The first value will be this
  510. * $coll and the final one will be an empty $coll, with the intervening
  511. * values the results of successive applications of `init`.
  512. *
  513. * @return an iterator over all the inits of this $coll
  514. * @example `List(1,2,3).inits = Iterator(List(1,2,3), List(1,2), List(1), Nil)`
  515. */
  516. def inits: Iterator[Repr] = iterateUntilEmpty(_.init)
  517. /** Copies elements of this $coll to an array.
  518. * Fills the given array `xs` with at most `len` elements of
  519. * this $coll, starting at position `start`.
  520. * Copying will stop once either the end of the current $coll is reached,
  521. * or the end of the array is reached, or `len` elements have been copied.
  522. *
  523. * $willNotTerminateInf
  524. *
  525. * @param xs the array to fill.
  526. * @param start the starting index.
  527. * @param len the maximal number of elements to copy.
  528. * @tparam B the type of the elements of the array.
  529. *
  530. *
  531. * @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit
  532. */
  533. def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
  534. var i = start
  535. val end = (start + len) min xs.length
  536. breakable {
  537. for (x <- this) {
  538. if (i >= end) break
  539. xs(i) = x
  540. i += 1
  541. }
  542. }
  543. }
  544. def toTraversable: Traversable[A] = thisCollection
  545. def toIterator: Iterator[A] = toStream.iterator
  546. def toStream: Stream[A] = toBuffer.toStream
  547. /** Converts this $coll to a string.
  548. *
  549. * @return a string representation of this collection. By default this
  550. * string consists of the `stringPrefix` of this $coll,
  551. * followed by all elements separated by commas and enclosed in parentheses.
  552. */
  553. override def toString = mkString(stringPrefix + "(", ", ", ")")
  554. /** Defines the prefix of this object's `toString` representation.
  555. *
  556. * @return a string representation which starts the result of `toString`
  557. * applied to this $coll. By default the string prefix is the
  558. * simple name of the collection class $coll.
  559. */
  560. def stringPrefix : String = {
  561. var string = repr.asInstanceOf[AnyRef].getClass.getName
  562. val idx1 = string.lastIndexOf('.' : Int)
  563. if (idx1 != -1) string = string.substring(idx1 + 1)
  564. val idx2 = string.indexOf('$')
  565. if (idx2 != -1) string = string.substring(0, idx2)
  566. string
  567. }
  568. /** Creates a non-strict view of this $coll.
  569. *
  570. * @return a non-strict view of this $coll.
  571. */
  572. def view = new TraversableView[A, Repr] {
  573. protected lazy val underlying = self.repr
  574. override def foreach[U](f: A => U) = self foreach f
  575. }
  576. /** Creates a non-strict view of a slice of this $coll.
  577. *
  578. * Note: the difference between `view` and `slice` is that `view` produces
  579. * a view of the current $coll, whereas `slice` produces a new $coll.
  580. *
  581. * Note: `view(from, to)` is equivalent to `view.slice(from, to)`
  582. * $orderDependent
  583. *
  584. * @param from the index of the first element of the view
  585. * @param until the index of the element following the view
  586. * @return a non-strict view of a slice of this $coll, starting at index `from`
  587. * and extending up to (but not including) index `until`.
  588. */
  589. def view(from: Int, until: Int): TraversableView[A, Repr] = view.slice(from, until)
  590. /** Creates a non-strict filter of this $coll.
  591. *
  592. * Note: the difference between `c filter p` and `c withFilter p` is that
  593. * the former creates a new collection, whereas the latter only
  594. * restricts the domain of subsequent `map`, `flatMap`, `foreach`,
  595. * and `withFilter` operations.
  596. * $orderDependent
  597. *
  598. * @param p the predicate used to test elements.
  599. * @return an object of class `WithFilter`, which supports
  600. * `map`, `flatMap`, `foreach`, and `withFilter` operations.
  601. * All these operations apply to those elements of this $coll which
  602. * satisfy the predicate `p`.
  603. */
  604. def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p)
  605. /** A class supporting filtered operations. Instances of this class are
  606. * returned by method `withFilter`.
  607. */
  608. class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] {
  609. /** Builds a new collection by applying a function to all elements of the
  610. * outer $coll containing this `WithFilter` instance that satisfy predicate `p`.
  611. *
  612. * @param f the function to apply to each element.
  613. * @tparam B the element type of the returned collection.
  614. * @tparam That $thatinfo
  615. * @param bf $bfinfo
  616. * @return a new collection of type `That` resulting from applying
  617. * the given function `f` to each element of the outer $coll
  618. * that satisfies predicate `p` and collecting the results.
  619. *
  620. * @usecase def map[B](f: A => B): $Coll[B]
  621. *
  622. * @return a new $coll resulting from applying the given function
  623. * `f` to each element of the outer $coll that satisfies
  624. * predicate `p` and collecting the results.
  625. */
  626. def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  627. val b = bf(repr)
  628. for (x <- self)
  629. if (p(x)) b += f(x)
  630. b.result
  631. }
  632. /** Builds a new collection by applying a function to all elements of the
  633. * outer $coll containing this `WithFilter` instance that satisfy
  634. * predicate `p` and concatenating the results.
  635. *
  636. * @param f the function to apply to each element.
  637. * @tparam B the element type of the returned collection.
  638. * @tparam That $thatinfo
  639. * @param bf $bfinfo
  640. * @return a new collection of type `That` resulting from applying
  641. * the given collection-valued function `f` to each element
  642. * of the outer $coll that satisfies predicate `p` and
  643. * concatenating the results.
  644. *
  645. * @usecase def flatMap[B](f: A => TraversableOnce[B]): $Coll[B]
  646. *
  647. * @return a new $coll resulting from applying the given collection-valued function
  648. * `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.
  649. */
  650. def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
  651. val b = bf(repr)
  652. for (x <- self)
  653. if (p(x)) b ++= f(x).seq
  654. b.result
  655. }
  656. /** Applies a function `f` to all elements of the outer $coll containing
  657. * this `WithFilter` instance that satisfy predicate `p`.
  658. *
  659. * @param f the function that is applied for its side-effect to every element.
  660. * The result of function `f` is discarded.
  661. *
  662. * @tparam U the type parameter describing the result of function `f`.
  663. * This result will always be ignored. Typically `U` is `Unit`,
  664. * but this is not necessary.
  665. *
  666. * @usecase def foreach(f: A => Unit): Unit
  667. */
  668. def foreach[U](f: A => U): Unit =
  669. for (x <- self)
  670. if (p(x)) f(x)
  671. /** Further refines the filter for this $coll.
  672. *
  673. * @param q the predicate used to test elements.
  674. * @return an object of class `WithFilter`, which supports
  675. * `map`, `flatMap`, `foreach`, and `withFilter` operations.
  676. * All these operations apply to those elements of this $coll which
  677. * satisfy the predicate `q` in addition to the predicate `p`.
  678. */
  679. def withFilter(q: A => Boolean): WithFilter =
  680. new WithFilter(x => p(x) && q(x))
  681. }
  682. // A helper for tails and inits.
  683. private def iterateUntilEmpty(f: Traversable[A @uV] => Traversable[A @uV]): Iterator[Repr] = {
  684. val it = Iterator.iterate(thisCollection)(f) takeWhile (x => !x.isEmpty)
  685. it ++ Iterator(Nil) map (newBuilder ++= _ result)
  686. }
  687. }
  688. </textarea>
  689. </form>
  690. <script>
  691. var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  692. lineNumbers: true,
  693. matchBrackets: true,
  694. theme: "ambiance",
  695. mode: "text/x-scala"
  696. });
  697. </script>
  698. </article>