2
0

scala.html 28 KB

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