2
2
** ________ ___ / / ___ Scala API **
3
** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL **
3
** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL **
4
4
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
5
5
** /____/\___/_/ |_/____/_/ | | **
9
9
package scala.collection
11
import mutable.{ Buffer, ListBuffer, ArrayBuffer }
12
import annotation.unchecked.{ uncheckedVariance => uV }
11
import mutable.{ Buffer, Builder, ListBuffer, ArrayBuffer }
12
import generic.CanBuildFrom
13
import scala.annotation.unchecked.{ uncheckedVariance => uV }
14
import scala.language.{implicitConversions, higherKinds}
15
import scala.reflect.ClassTag
14
17
/** A template trait for collections which can be traversed either once only
15
18
* or one or more times.
16
19
* $traversableonceinfo
18
* @tparam A the element type of the collection
20
21
* @author Martin Odersky
21
22
* @author Paul Phillips
57
58
* Note: will not terminate for infinite-sized collections.
59
trait TraversableOnce[+A] extends GenTraversableOnce[A] {
60
trait TraversableOnce[+A] extends Any with GenTraversableOnce[A] {
62
63
/** Self-documenting abstract methods. */
124
125
* @param pf the partial function
125
126
* @return an option value containing pf applied to the first
126
127
* value for which it is defined, or `None` if none exists.
127
* @example `Seq("a", 1, 5L).collectFirst({ case x: Int => x*10 }) = Some(10)`
128
* @example `Seq("a", 1, 5L).collectFirst({ case x: Int => x*10 }) = Some(10)`
129
130
def collectFirst[B](pf: PartialFunction[A, B]): Option[B] = {
130
131
for (x <- self.toIterator) { // make sure to use an iterator or `seq`
147
148
def foldRight[B](z: B)(op: (A, B) => B): B =
148
149
reversed.foldLeft(z)((x, y) => op(y, x))
151
/** Applies a binary operator to all elements of this $coll,
152
* going left to right.
153
* $willNotTerminateInf
154
* $orderDependentFold
156
* @param op the binary operator.
157
* @tparam B the result type of the binary operator.
158
* @return the result of inserting `op` between consecutive elements of this $coll,
159
* going left to right:
161
* op( op( ... op(x_1, x_2) ..., x_{n-1}), x_n)
163
* where `x,,1,,, ..., x,,n,,` are the elements of this $coll.
164
* @throws `UnsupportedOperationException` if this $coll is empty. */
150
165
def reduceLeft[B >: A](op: (B, A) => B): B = {
152
167
throw new UnsupportedOperationException("empty.reduceLeft")
228
243
def copyToArray[B >: A](xs: Array[B]): Unit =
229
244
copyToArray(xs, 0, xs.length)
231
def toArray[B >: A : ClassManifest]: Array[B] = {
246
def toArray[B >: A : ClassTag]: Array[B] = {
232
247
if (isTraversableAgain) {
233
248
val result = new Array[B](size)
234
249
copyToArray(result, 0)
240
255
def toTraversable: Traversable[A]
242
def toList: List[A] = new ListBuffer[A] ++= seq toList
257
def toList: List[A] = to[List]
244
259
def toIterable: Iterable[A] = toStream
246
261
def toSeq: Seq[A] = toStream
248
def toIndexedSeq[B >: A]: immutable.IndexedSeq[B] = immutable.IndexedSeq() ++ seq
250
def toBuffer[B >: A]: mutable.Buffer[B] = new ArrayBuffer[B] ++= seq
252
def toSet[B >: A]: immutable.Set[B] = immutable.Set() ++ seq
263
def toIndexedSeq: immutable.IndexedSeq[A] = to[immutable.IndexedSeq]
265
def toBuffer[B >: A]: mutable.Buffer[B] = to[ArrayBuffer].asInstanceOf[mutable.Buffer[B]]
267
def toSet[B >: A]: immutable.Set[B] = to[immutable.Set].asInstanceOf[immutable.Set[B]]
269
def toVector: Vector[A] = to[Vector]
271
def to[Col[_]](implicit cbf: CanBuildFrom[Nothing, A, Col[A @uV]]): Col[A @uV] = {
254
277
def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U] = {
255
278
val b = immutable.Map.newBuilder[T, U]
267
290
def mkString: String = mkString("")
269
/** Appends all elements of this $coll to a string builder using start, end,
270
* and separator strings.
271
* The written text begins with the string `start` and ends with the string
272
* `end`. Inside, the string representations (w.r.t. the method `toString`)
292
/** Appends all elements of this $coll to a string builder using start, end, and separator strings.
293
* The written text begins with the string `start` and ends with the string `end`.
294
* Inside, the string representations (w.r.t. the method `toString`)
273
295
* of all elements of this $coll are separated by the string `sep`.
313
/** Appends all elements of this $coll to a string builder using a separator
314
* string. The written text consists of the string representations (w.r.t.
315
* the method `toString`) of all elements of this $coll, separated by the
335
/** Appends all elements of this $coll to a string builder using a separator string.
336
* The written text consists of the string representations (w.r.t. the method `toString`)
337
* of all elements of this $coll, separated by the string `sep`.
362
382
object TraversableOnce {
363
implicit def traversableOnceCanBuildFrom[T] = new OnceCanBuildFrom[T]
364
implicit def wrapTraversableOnce[A](trav: TraversableOnce[A]) = new MonadOps(trav)
383
@deprecated("use OnceCanBuildFrom instead", "2.10.0")
384
def traversableOnceCanBuildFrom[T] = new OnceCanBuildFrom[T]
385
@deprecated("use MonadOps instead", "2.10.0")
386
def wrapTraversableOnce[A](trav: TraversableOnce[A]) = new MonadOps(trav)
388
implicit def alternateImplicit[A](trav: TraversableOnce[A]) = new ForceImplicitAmbiguity
365
389
implicit def flattenTraversableOnce[A, CC[_]](travs: TraversableOnce[CC[A]])(implicit ev: CC[A] => TraversableOnce[A]) =
366
390
new FlattenOps[A](travs map ev)
368
/** With the advent of TraversableOnce, it can be useful to have a builder which
369
* operates on Iterators so they can be treated uniformly along with the collections.
370
* See scala.util.Random.shuffle for an example.
372
class OnceCanBuildFrom[A] extends generic.CanBuildFrom[TraversableOnce[A], A, TraversableOnce[A]] {
373
def newIterator = new ArrayBuffer[A] mapResult (_.iterator)
392
/* Functionality reused in Iterator.CanBuildFrom */
393
private[collection] abstract class BufferedCanBuildFrom[A, Coll[X] <: TraversableOnce[X]] extends generic.CanBuildFrom[Coll[_], A, Coll[A]] {
394
def bufferToColl[B](buff: ArrayBuffer[B]): Coll[B]
395
def traversableToColl[B](t: GenTraversable[B]): Coll[B]
397
def newIterator: Builder[A, Coll[A]] = new ArrayBuffer[A] mapResult bufferToColl
375
399
/** Creates a new builder on request of a collection.
376
400
* @param from the collection requesting the builder to be created.
377
401
* @return the result of invoking the `genericBuilder` method on `from`.
379
def apply(from: TraversableOnce[A]) = newIterator
403
def apply(from: Coll[_]): Builder[A, Coll[A]] = from match {
404
case xs: generic.GenericTraversableTemplate[_, _] => xs.genericBuilder.asInstanceOf[Builder[A, Traversable[A]]] mapResult {
405
case res => traversableToColl(res.asInstanceOf[GenTraversable[A]])
407
case _ => newIterator
381
410
/** Creates a new builder from scratch
382
411
* @return the result of invoking the `newBuilder` method of this factory.
384
413
def apply() = newIterator
416
/** With the advent of `TraversableOnce`, it can be useful to have a builder which
417
* operates on `Iterator`s so they can be treated uniformly along with the collections.
418
* See `scala.util.Random.shuffle` or `scala.concurrent.Future.sequence` for an example.
420
class OnceCanBuildFrom[A] extends BufferedCanBuildFrom[A, TraversableOnce] {
421
def bufferToColl[B](buff: ArrayBuffer[B]) = buff.iterator
422
def traversableToColl[B](t: GenTraversable[B]) = t.seq
425
/** Evidence for building collections from `TraversableOnce` collections */
426
implicit def OnceCanBuildFrom[A] = new OnceCanBuildFrom[A]
387
428
class FlattenOps[A](travs: TraversableOnce[TraversableOnce[A]]) {
388
def flatten: Iterator[A] = new Iterator[A] {
429
def flatten: Iterator[A] = new AbstractIterator[A] {
389
430
val its = travs.toIterator
390
431
private var it: Iterator[A] = Iterator.empty
391
432
def hasNext: Boolean = it.hasNext || its.hasNext && { it = its.next.toIterator; hasNext }
396
class MonadOps[+A](trav: TraversableOnce[A]) {
437
class ForceImplicitAmbiguity
439
implicit class MonadOps[+A](trav: TraversableOnce[A]) {
397
440
def map[B](f: A => B): TraversableOnce[B] = trav.toIterator map f
398
441
def flatMap[B](f: A => GenTraversableOnce[B]): TraversableOnce[B] = trav.toIterator flatMap f
399
442
def withFilter(p: A => Boolean) = trav.toIterator filter p