This repository has been archived by the owner on Dec 22, 2021. It is now read-only.
/
Iterable.scala
1260 lines (1136 loc) · 50.2 KB
/
Iterable.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package strawman
package collection
import scala.annotation.unchecked.uncheckedVariance
import scala.language.implicitConversions
import scala.reflect.ClassTag
import scala.{Any, AnyRef, Array, Boolean, Either, `inline`, Int, None, Numeric, Option, Ordering, PartialFunction, StringContext, Some, Unit, deprecated, IllegalArgumentException, Function1, deprecatedOverriding}
import java.lang.{String, UnsupportedOperationException}
import scala.Predef.<:<
import strawman.collection.mutable.{ArrayBuffer, Builder, StringBuilder}
import java.lang.String
/** Base trait for generic collections.
*
* @tparam A the element type of the collection
*
* @define Coll `Iterable`
* @define coll iterable collection
*/
trait Iterable[+A] extends IterableOnce[A] with IterableOps[A, Iterable, Iterable[A]] with Traversable[A] {
// The collection itself
final def toIterable: this.type = this
//TODO scalac generates an override for this in AbstractMap; Making it final leads to a VerifyError
protected[this] def coll: this.type = this
protected[this] def fromSpecificIterable(coll: Iterable[A]): IterableCC[A] = iterableFactory.from(coll)
protected[this] def newSpecificBuilder(): Builder[A, IterableCC[A]] = iterableFactory.newBuilder[A]()
def iterableFactory: IterableFactory[IterableCC] = Iterable
}
/** Base trait for Iterable operations
*
* =VarianceNote=
*
* We require that for all child classes of Iterable the variance of
* the child class and the variance of the `C` parameter passed to `IterableOps`
* are the same. We cannot express this since we lack variance polymorphism. That's
* why we have to resort at some places to write `C[A @uncheckedVariance]`.
*
* @tparam CC type constructor of the collection (e.g. `List`, `Set`). Operations returning a collection
* with a different type of element `B` (e.g. `map`) return a `CC[B]`.
* @tparam C type of the collection (e.g. `List[Int]`, `String`, `BitSet`). Operations returning a collection
* with the same type of element (e.g. `drop`, `filter`) return a `C`.
*
* @define Coll Iterable
* @define coll iterable collection
* @define orderDependent
*
* Note: might return different results for different runs, unless the underlying collection type is ordered.
* @define orderDependentFold
*
* Note: might return different results for different runs, unless the
* underlying collection type is ordered or the operator is associative
* and commutative.
* @define mayNotTerminateInf
*
* Note: may not terminate for infinite-sized collections.
* @define willNotTerminateInf
*
* Note: will not terminate for infinite-sized collections.
* @define undefinedorder
* The order in which operations are performed on elements is unspecified
* and may be nondeterministic.
*/
trait IterableOps[+A, +CC[_], +C] extends Any with IterableOnce[A] {
protected[this] type IterableCC[X] = CC[X]
/**
* @return This collection as an `Iterable[A]`. No new collection will be built if `this` is already an `Iterable[A]`.
*/
def toIterable: Iterable[A]
/**
* @return This collection as a `C`.
*/
protected[this] def coll: C
/**
* Defines how to turn a given `Iterable[A]` into a collection of type `C`.
*
* This process can be done in a strict way or a non-strict way (ie. without evaluating
* the elements of the resulting collections). In other words, this methods defines
* the evaluation model of the collection.
*/
protected[this] def fromSpecificIterable(coll: Iterable[A]): C
/** Similar to `fromSpecificIterable`, but for a (possibly) different type of element.
* Note that the return type is know `CC[E]`.
*/
@`inline` final protected[this] def fromIterable[E](it: Iterable[E]): CC[E] = iterableFactory.from(it)
/**
* @return The companion object of this ${coll}, providing various factory methods.
*/
def iterableFactory: IterableFactory[IterableCC]
/**
* @return a strict builder for the same collection type.
*
* Note that in the case of lazy collections (e.g. [[View]] or [[immutable.LazyList]]),
* it is possible to implement this method but the resulting `Builder` will break laziness.
* As a consequence, operations should preferably be implemented with `fromSpecificIterable`
* instead of this method.
*/
protected[this] def newSpecificBuilder(): Builder[A, C]
// Consumes all the collection!
protected[this] def reversed: Iterable[A] = {
var xs: immutable.List[A] = immutable.Nil
val it = iterator()
while (it.hasNext) xs = it.next() :: xs
xs
}
/** Apply `f` to each element for its side effects
* Note: [U] parameter needed to help scalac's type inference.
*/
def foreach[U](f: A => U): Unit = iterator().foreach(f)
/** Tests whether a predicate holds for all elements of this $coll.
*
* $mayNotTerminateInf
*
* @param p the predicate used to test elements.
* @return `true` if this $coll is empty or the given predicate `p`
* holds for all elements of this $coll, otherwise `false`.
*/
def forall(p: A => Boolean): Boolean = iterator().forall(p)
/** Tests whether a predicate holds for at least one element of this $coll.
*
* $mayNotTerminateInf
*
* @param p the predicate used to test elements.
* @return `true` if the given predicate `p` is satisfied by at least one element of this $coll, otherwise `false`
*/
def exists(p: A => Boolean): Boolean = iterator().exists(p)
/** Counts the number of elements in the $coll which satisfy a predicate.
*
* @param p the predicate used to test elements.
* @return the number of elements satisfying the predicate `p`.
*/
def count(p: A => Boolean): Int = iterator().count(p)
/** Finds the first element of the $coll satisfying a predicate, if any.
*
* $mayNotTerminateInf
* $orderDependent
*
* @param p the predicate used to test elements.
* @return an option value containing the first element in the $coll
* that satisfies `p`, or `None` if none exists.
*/
def find(p: A => Boolean): Option[A] = iterator().find(p)
/** Applies a binary operator to a start value and all elements of this $coll,
* going left to right.
*
* $willNotTerminateInf
* $orderDependentFold
*
* @param z the start value.
* @param op the binary operator.
* @tparam B the result type of the binary operator.
* @return the result of inserting `op` between consecutive elements of this $coll,
* going left to right with the start value `z` on the left:
* {{{
* op(...op(z, x_1), x_2, ..., x_n)
* }}}
* where `x,,1,,, ..., x,,n,,` are the elements of this $coll.
* Returns `z` if this $coll is empty.
*/
def foldLeft[B](z: B)(op: (B, A) => B): B = iterator().foldLeft(z)(op)
/** Applies a binary operator to all elements of this $coll and a start value,
* going right to left.
*
* $willNotTerminateInf
* $orderDependentFold
* @param z the start value.
* @param op the binary operator.
* @tparam B the result type of the binary operator.
* @return the result of inserting `op` between consecutive elements of this $coll,
* going right to left with the start value `z` on the right:
* {{{
* op(x_1, op(x_2, ... op(x_n, z)...))
* }}}
* where `x,,1,,, ..., x,,n,,` are the elements of this $coll.
* Returns `z` if this $coll is empty.
*/
def foldRight[B](z: B)(op: (A, B) => B): B = iterator().foldRight(z)(op)
@deprecated("Use foldLeft instead of /:", "2.13.0")
@`inline` final def /: [B](z: B)(op: (B, A) => B): B = foldLeft[B](z)(op)
@deprecated("Use foldRight instead of :\\", "2.13.0")
@`inline` final def :\ [B](z: B)(op: (A, B) => B): B = foldRight[B](z)(op)
/** Reduces the elements of this $coll using the specified associative binary operator.
*
* $undefinedorder
*
* @tparam B A type parameter for the binary operator, a supertype of `A`.
* @param op A binary operator that must be associative.
* @return The result of applying reduce operator `op` between all the elements if the $coll is nonempty.
* @throws UnsupportedOperationException
* if this $coll is empty.
*/
def reduce[B >: A](op: (B, B) => B): B = iterator().reduce(op)
/** Reduces the elements of this $coll, if any, using the specified
* associative binary operator.
*
* $undefinedorder
*
* @tparam B A type parameter for the binary operator, a supertype of `A`.
* @param op A binary operator that must be associative.
* @return An option value containing result of applying reduce operator `op` between all
* the elements if the collection is nonempty, and `None` otherwise.
*/
def reduceOption[B >: A](op: (B, B) => B): Option[B] = iterator().reduceOption(op)
/** Applies a binary operator to all elements of this $coll,
* going left to right.
* $willNotTerminateInf
* $orderDependentFold
*
* @param op the binary operator.
* @tparam B the result type of the binary operator.
* @return the result of inserting `op` between consecutive elements of this $coll,
* going left to right:
* {{{
* op( op( ... op(x_1, x_2) ..., x_{n-1}), x_n)
* }}}
* where `x,,1,,, ..., x,,n,,` are the elements of this $coll.
* @throws UnsupportedOperationException if this $coll is empty. */
def reduceLeft[B >: A](op: (B, A) => B): B = iterator().reduceLeft(op)
/** Applies a binary operator to all elements of this $coll, going right to left.
* $willNotTerminateInf
* $orderDependentFold
*
* @param op the binary operator.
* @tparam B the result type of the binary operator.
* @return the result of inserting `op` between consecutive elements of this $coll,
* going right to left:
* {{{
* op(x_1, op(x_2, ..., op(x_{n-1}, x_n)...))
* }}}
* where `x,,1,,, ..., x,,n,,` are the elements of this $coll.
* @throws UnsupportedOperationException if this $coll is empty.
*/
def reduceRight[B >: A](op: (A, B) => B): B = iterator().reduceRight(op)
/** Optionally applies a binary operator to all elements of this $coll, going left to right.
* $willNotTerminateInf
* $orderDependentFold
*
* @param op the binary operator.
* @tparam B the result type of the binary operator.
* @return an option value containing the result of `reduceLeft(op)` if this $coll is nonempty,
* `None` otherwise.
*/
def reduceLeftOption[B >: A](op: (B, A) => B): Option[B] = iterator().reduceLeftOption(op)
/** Optionally applies a binary operator to all elements of this $coll, going
* right to left.
* $willNotTerminateInf
* $orderDependentFold
*
* @param op the binary operator.
* @tparam B the result type of the binary operator.
* @return an option value containing the result of `reduceRight(op)` if this $coll is nonempty,
* `None` otherwise.
*/
def reduceRightOption[B >: A](op: (A, B) => B): Option[B] = iterator().reduceRightOption(op)
/** Tests whether the $coll is empty.
*
* Note: Implementations in subclasses that are not repeatedly traversable must take
* care not to consume any elements when `isEmpty` is called.
*
* @return `true` if the $coll contains no elements, `false` otherwise.
*/
def isEmpty: Boolean = !iterator().hasNext
/** Tests whether the $coll is not empty.
*
* @return `true` if the $coll contains at least one element, `false` otherwise.
*/
@deprecatedOverriding("nonEmpty is defined as !isEmpty; override isEmpty instead", "2.13.0")
def nonEmpty: Boolean = !isEmpty
/** Selects the first element of this $coll.
* $orderDependent
* @return the first element of this $coll.
* @throws NoSuchElementException if the $coll is empty.
*/
def head: A = iterator().next()
/** Optionally selects the first element.
* $orderDependent
* @return the first element of this $coll if it is nonempty,
* `None` if it is empty.
*/
def headOption: Option[A] = {
val it = iterator()
if(it.hasNext) Some(it.next()) else None
}
/** Selects the last element.
* $orderDependent
* @return The last element of this $coll.
* @throws NoSuchElementException If the $coll is empty.
*/
def last: A = {
val it = iterator()
var lst = it.next()
while (it.hasNext) lst = it.next()
lst
}
/** Optionally selects the last element.
* $orderDependent
* @return the last element of this $coll$ if it is nonempty,
* `None` if it is empty.
*/
def lastOption: Option[A] = if (isEmpty) None else Some(last)
/** The number of elements in this collection, if it can be cheaply computed,
* -1 otherwise. Cheaply usually means: Not requiring a collection traversal.
*/
def knownSize: Int = -1
@deprecated("Use .knownSize >=0 instead of .hasDefiniteSize", "2.13.0")
@`inline` final def hasDefiniteSize = knownSize >= 0
/** The size of this $coll.
*
* $willNotTerminateInf
*
* @return the number of elements in this $coll.
*/
def size: Int = if (knownSize >= 0) knownSize else iterator().length
/** A view over the elements of this collection. */
def view: View[A] = View.fromIteratorProvider(() => iterator())
/** A view over a slice of the elements of this collection. */
@deprecated("Use .view.slice(from, until) instead of .view(from, until)", "2.13.0")
@`inline` final def view(from: Int, until: Int): View[A] = view.slice(from, until)
/** Given a collection factory `factory`, convert this collection to the appropriate
* representation for the current element type `A`. Example uses:
*
* xs.to(List)
* xs.to(ArrayBuffer)
* xs.to(BitSet) // for xs: Iterable[Int]
*/
def to[C1](factory: Factory[A, C1]): C1 = factory.fromSpecific(this)
def toList: immutable.List[A] = immutable.List.from(this)
def toVector: immutable.Vector[A] = immutable.Vector.from(this)
def toMap[K, V](implicit ev: A <:< (K, V)): immutable.Map[K, V] =
immutable.Map.from(this.asInstanceOf[IterableOnce[(K, V)]])
def toSet[B >: A]: immutable.Set[B] = immutable.Set.from(this)
def toSeq: immutable.Seq[A] = immutable.Seq.from(this)
def toIndexedSeq: immutable.IndexedSeq[A] = immutable.IndexedSeq.from(this)
@deprecated("Use Stream.from(it) instead of it.toStream", "2.13.0")
@`inline` final def toStream: immutable.Stream[A] = immutable.Stream.from(this)
@deprecated("Use ArrayBuffer.from(it) instead of it.toBuffer", "2.13.0")
@`inline` final def toBuffer[B >: A]: mutable.Buffer[B] = mutable.ArrayBuffer.from(this)
@deprecated("Use .iterator() instead of .toIterator", "2.13.0")
@`inline` final def toIterator: Iterator[A] = iterator()
/** Convert collection to array. */
def toArray[B >: A: ClassTag]: Array[B] =
if (knownSize >= 0) copyToArray(new Array[B](knownSize), 0)
else ArrayBuffer.from(this).toArray[B]
/** Copy elements of this collection to an array.
* Fills the given array `xs` starting at index `start`.
* Copying will stop once either the all elements of this collection have been copied,
* or the end of the array is reached.
*
* @param xs the array to fill.
* @param start the starting index.
* @tparam B the type of the elements of the array.
*
* @usecase def copyToArray(xs: Array[A], start: Int): Unit
*
* $willNotTerminateInf
*/
def copyToArray[B >: A](xs: Array[B], start: Int = 0): xs.type = iterator().copyToArray(xs, start)
/** Copy elements of this collection to an array.
* Fills the given array `xs` starting at index `start` with at most
* `len` values produced by this iterator.
* Copying will stop once either the all elements of this collection have been copied,
* or the end of the array is reached, or `len` elements have been copied.
*
* @param xs the array to fill.
* @param start the starting index.
* @param len the maximal number of elements to copy.
* @tparam B the type of the elements of the array.
*
* @note Reuse: $consumesIterator
*
* @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit
*
* $willNotTerminateInf
*/
def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): xs.type = iterator().copyToArray(xs, start, len)
/** Defines the prefix of this object's `toString` representation.
*
* It is recommended to return the name of the concrete collection type, but
* not implementation subclasses. For example, for `ListMap` this method should
* return `"ListMap"`, not `"Map"` (the supertype) or `"Node"` (an implementation
* subclass).
*
* It is recommended to overwrite this method even if the default implementation
* returns the correct name, to avoid the implementation using reflection.
*
* @return a string representation which starts the result of `toString`
* applied to this $coll. By default the string prefix is the
* simple name of the collection class $coll.
*/
def className: String = {
/* This method is written in a style that avoids calling `String.split()`
* as well as methods of java.lang.Character that require the Unicode
* database information. This is mostly important for Scala.js, so that
* using the collection library does automatically bring java.util.regex.*
* and the Unicode database in the generated code.
*
* This algorithm has the additional benefit that it won't allocate
* anything except the result String in the common case, where the class
* is not an inner class (i.e., when the result contains no '.').
*/
val fqn = toIterable.getClass.getName
var pos: Int = fqn.length - 1
// Skip trailing $'s
while (pos != -1 && fqn.charAt(pos) == '$') {
pos -= 1
}
if (pos == -1 || fqn.charAt(pos) == '.') {
return ""
}
var result: String = ""
while (true) {
// Invariant: if we enter the loop, there is a non-empty part
// Look for the beginning of the part, remembering where was the last non-digit
val partEnd = pos + 1
while (pos != -1 && fqn.charAt(pos) <= '9' && fqn.charAt(pos) >= '0') {
pos -= 1
}
val lastNonDigit = pos
while (pos != -1 && fqn.charAt(pos) != '$' && fqn.charAt(pos) != '.') {
pos -= 1
}
val partStart = pos + 1
// A non-last part which contains only digits marks a method-local part -> drop the prefix
if (pos == lastNonDigit && partEnd != fqn.length) {
return result
}
// Skip to the next part, and determine whether we are the end
while (pos != -1 && fqn.charAt(pos) == '$') {
pos -= 1
}
val atEnd = pos == -1 || fqn.charAt(pos) == '.'
// Handle the actual content of the part (we ignore parts that are likely synthetic)
def isPartLikelySynthetic = {
val firstChar = fqn.charAt(partStart)
(firstChar > 'Z' && firstChar < 0x7f) || (firstChar < 'A')
}
if (atEnd || !isPartLikelySynthetic) {
val part = fqn.substring(partStart, partEnd)
result = if (result.isEmpty) part else part + '.' + result
if (atEnd)
return result
}
}
// dead code
result
}
@deprecated("Use className instead of stringPrefix", "2.13.0")
@`inline` final def stringPrefix: String = className
/** Displays all elements of this $coll in a string using start, end, and
* separator strings.
*
* @param start the starting string.
* @param sep the separator string.
* @param end the ending string.
* @return a string representation of this $coll. The resulting string
* begins with the string `start` and ends with the string
* `end`. Inside, the string representations (w.r.t. the method
* `toString`) of all elements of this $coll are separated by
* the string `sep`.
*
* @example `List(1, 2, 3).mkString("(", "; ", ")") = "(1; 2; 3)"`
*/
def mkString(start: String, sep: String, end: String): String = {
var first: Boolean = true
val b = new StringBuilder()
b ++= start
foreach { elem =>
if (!first) b ++= sep
first = false
b ++= String.valueOf(elem)
}
b ++= end
b.result()
}
/** Displays all elements of this $coll in a string using a separator string.
*
* @param sep the separator string.
* @return a string representation of this $coll. In the resulting string
* the string representations (w.r.t. the method `toString`)
* of all elements of this $coll are separated by the string `sep`.
*
* @example `List(1, 2, 3).mkString("|") = "1|2|3"`
*/
def mkString(sep: String): String = mkString("", sep, "")
/** Displays all elements of this $coll in a string.
*
* @return a string representation of this $coll. In the resulting string
* the string representations (w.r.t. the method `toString`)
* of all elements of this $coll follow each other without any
* separator string.
*/
def mkString: String = mkString("")
/** Converts this $coll to a string.
*
* @return a string representation of this collection. By default this
* string consists of the `className` of this $coll, followed
* by all elements separated by commas and enclosed in parentheses.
*/
override def toString = mkString(className + "(", ", ", ")")
//TODO Can there be a useful lazy implementation of this method? Otherwise mark it as being always strict
/** Transposes this $coll of iterable collections into
* a $coll of ${coll}s.
*
* The resulting collection's type will be guided by the
* static type of $coll. For example:
*
* {{{
* val xs = List(
* Set(1, 2, 3),
* Set(4, 5, 6)).transpose
* // xs == List(
* // List(1, 4),
* // List(2, 5),
* // List(3, 6))
*
* val ys = Vector(
* List(1, 2, 3),
* List(4, 5, 6)).transpose
* // ys == Vector(
* // Vector(1, 4),
* // Vector(2, 5),
* // Vector(3, 6))
* }}}
*
* @tparam B the type of the elements of each iterable collection.
* @param asIterable an implicit conversion which asserts that the
* element type of this $coll is an `Iterable`.
* @return a two-dimensional $coll of ${coll}s which has as ''n''th row
* the ''n''th column of this $coll.
* @throws IllegalArgumentException if all collections in this $coll
* are not of the same size.
*/
def transpose[B](implicit asIterable: A => /*<:<!!!*/ Iterable[B]): CC[CC[B] @uncheckedVariance] = {
if (isEmpty)
return iterableFactory.empty[CC[B]]
def fail = throw new IllegalArgumentException("transpose requires all collections have the same size")
val headSize = asIterable(head).size
val bs: strawman.collection.immutable.IndexedSeq[Builder[B, CC[B]]] = strawman.collection.immutable.IndexedSeq.fill(headSize)(iterableFactory.newBuilder[B]())
for (xs <- iterator()) {
var i = 0
for (x <- asIterable(xs)) {
if (i >= headSize) fail
bs(i) += x
i += 1
}
if (i != headSize)
fail
}
fromIterable(bs.map(_.result()))
}
/** Sums up the elements of this collection.
*
* @param num an implicit parameter defining a set of numeric operations
* which includes the `+` operator to be used in forming the sum.
* @tparam B the result type of the `+` operator.
* @return the sum of all elements of this $coll with respect to the `+` operator in `num`.
*
* @usecase def sum: A
* @inheritdoc
*
* @return the sum of all elements in this $coll of numbers of type `Int`.
* Instead of `Int`, any other type `T` with an implicit `Numeric[T]` implementation
* can be used as element type of the $coll and as result type of `sum`.
* Examples of such types are: `Long`, `Float`, `Double`, `BigInt`.
*
*/
def sum[B >: A](implicit num: Numeric[B]): B = iterator().sum[B]
/** Multiplies up the elements of this collection.
*
* @param num an implicit parameter defining a set of numeric operations
* which includes the `*` operator to be used in forming the product.
* @tparam B the result type of the `*` operator.
* @return the product of all elements of this $coll with respect to the `*` operator in `num`.
*
* @usecase def product: A
* @inheritdoc
*
* @return the product of all elements in this $coll of numbers of type `Int`.
* Instead of `Int`, any other type `T` with an implicit `Numeric[T]` implementation
* can be used as element type of the $coll and as result type of `product`.
* Examples of such types are: `Long`, `Float`, `Double`, `BigInt`.
*/
def product[B >: A](implicit num: Numeric[B]): B = iterator().product[B]
/** Finds the smallest element.
*
* @param ord An ordering to be used for comparing elements.
* @tparam B The type over which the ordering is defined.
* @return the smallest element of this $coll with respect to the ordering `ord`.
*
* @usecase def min: A
* @inheritdoc
*
* @return the smallest element of this $coll
*/
def min[B >: A](implicit ord: Ordering[B]): A = iterator().min[B]
/** Finds the largest element.
*
* @param ord An ordering to be used for comparing elements.
* @tparam B The type over which the ordering is defined.
* @return the largest element of this $coll with respect to the ordering `ord`.
*
* @usecase def max: A
* @inheritdoc
*
* @return the largest element of this $coll.
*/
def max[B >: A](implicit ord: Ordering[B]): A = iterator().max[B]
/** Finds the first element which yields the largest value measured by function f.
*
* @param cmp An ordering to be used for comparing elements.
* @tparam B The result type of the function f.
* @param f The measuring function.
* @return the first element of this $coll with the largest value measured by function f
* with respect to the ordering `cmp`.
*
* @usecase def maxBy[B](f: A => B): A
* @inheritdoc
*
* @return the first element of this $coll with the largest value measured by function f.
*/
def maxBy[B](f: A => B)(implicit cmp: Ordering[B]): A = iterator().maxBy(f)
/** Finds the first element which yields the smallest value measured by function f.
*
* @param cmp An ordering to be used for comparing elements.
* @tparam B The result type of the function f.
* @param f The measuring function.
* @return the first element of this $coll with the smallest value measured by function f
* with respect to the ordering `cmp`.
*
* @usecase def minBy[B](f: A => B): A
* @inheritdoc
*
* @return the first element of this $coll with the smallest value measured by function f.
*/
def minBy[B](f: A => B)(implicit cmp: Ordering[B]): A = iterator().minBy(f)
/** Selects all elements of this $coll which satisfy a predicate.
*
* @param pred the predicate used to test elements.
* @return a new $coll consisting of all elements of this $coll that satisfy the given
* predicate `pred`. Their order may not be preserved.
*/
def filter(pred: A => Boolean): C = fromSpecificIterable(View.Filter(toIterable, pred, isFlipped = false))
/** Selects all elements of this $coll which do not satisfy a predicate.
*
* @param pred the predicate used to test elements.
* @return a new $coll consisting of all elements of this $coll that do not satisfy the given
* predicate `pred`. Their order may not be preserved.
*/
def filterNot(pred: A => Boolean): C = fromSpecificIterable(View.Filter(toIterable, pred, isFlipped = true))
/** Creates a non-strict filter of this $coll.
*
* Note: the difference between `c filter p` and `c withFilter p` is that
* the former creates a new collection, whereas the latter only
* restricts the domain of subsequent `map`, `flatMap`, `foreach`,
* and `withFilter` operations.
* $orderDependent
*
* @param p the predicate used to test elements.
* @return an object of class `WithFilter`, which supports
* `map`, `flatMap`, `foreach`, and `withFilter` operations.
* All these operations apply to those elements of this $coll
* which satisfy the predicate `p`.
*/
def withFilter(p: A => Boolean): collection.WithFilter[A, CC] = new WithFilter(p)
/** A template trait that contains just the `map`, `flatMap`, `foreach` and `withFilter` methods
* of trait `Iterable`.
*
* @define coll iterable collection
*/
class WithFilter(p: A => Boolean) extends collection.WithFilter[A, CC] {
protected[this] def filtered = View.Filter(toIterable, p, isFlipped = false)
def map[B](f: A => B): CC[B] = iterableFactory.from(View.Map(filtered, f))
def flatMap[B](f: A => IterableOnce[B]): CC[B] = iterableFactory.from(View.FlatMap(filtered, f))
def foreach[U](f: A => U): Unit = filtered.foreach(f)
def withFilter(q: A => Boolean): WithFilter = new WithFilter(a => p(a) && q(a))
}
/** A pair of, first, all elements that satisfy prediacte `p` and, second,
* all elements that do not. Interesting because it splits a collection in two.
*
* The default implementation provided here needs to traverse the collection twice.
* Strict collections have an overridden version of `partition` in `Buildable`,
* which requires only a single traversal.
*/
def partition(p: A => Boolean): (C, C) = {
val pn = View.Partition(toIterable, p)
(fromSpecificIterable(pn.first), fromSpecificIterable(pn.second))
}
/** Splits this $coll into two at a given position.
* Note: `c splitAt n` is equivalent to (but possibly more efficient than)
* `(c take n, c drop n)`.
* $orderDependent
*
* @param n the position at which to split.
* @return a pair of ${coll}s consisting of the first `n`
* elements of this $coll, and the other elements.
*/
def splitAt(n: Int): (C, C) = (take(n), drop(n))
/** A collection containing the first `n` elements of this collection. */
def take(n: Int): C = fromSpecificIterable(View.Take(toIterable, n))
/** A collection containing the last `n` elements of this collection. */
def takeRight(n: Int): C = {
val b = newSpecificBuilder()
b.sizeHintBounded(n, toIterable)
val lead = iterator() drop n
val it = iterator()
while (lead.hasNext) {
lead.next()
it.next()
}
while (it.hasNext) b += it.next()
b.result()
}
/** Takes longest prefix of elements that satisfy a predicate.
* $orderDependent
* @param p The predicate used to test elements.
* @return the longest prefix of this $coll whose elements all satisfy
* the predicate `p`.
*/
def takeWhile(p: A => Boolean): C = fromSpecificIterable(View.TakeWhile(toIterable, p))
/** Splits this $coll into a prefix/suffix pair according to a predicate.
*
* Note: `c span p` is equivalent to (but possibly more efficient than)
* `(c takeWhile p, c dropWhile p)`, provided the evaluation of the
* predicate `p` does not cause any side-effects.
* $orderDependent
*
* @param p the test predicate
* @return a pair consisting of the longest prefix of this $coll whose
* elements all satisfy `p`, and the rest of this $coll.
*/
def span(p: A => Boolean): (C, C) = (takeWhile(p), dropWhile(p))
/** The rest of the collection without its `n` first elements. For
* linear, immutable collections this should avoid making a copy.
*/
def drop(n: Int): C = fromSpecificIterable(View.Drop(toIterable, n))
/** The rest of the collection without its `n` last elements. For
* linear, immutable collections this should avoid making a copy.
*/
def dropRight(n: Int): C = {
val b = newSpecificBuilder()
if (n >= 0) b.sizeHint(toIterable, delta = -n)
val lead = iterator() drop n
val it = iterator()
while (lead.hasNext) {
b += it.next()
lead.next()
}
b.result()
}
/** Drops longest prefix of elements that satisfy a predicate.
* $orderDependent
* @param p The predicate used to test elements.
* @return the longest suffix of this $coll whose first element
* does not satisfy the predicate `p`.
*/
def dropWhile(p: A => Boolean): C = fromSpecificIterable(View.DropWhile(toIterable, p))
/** Partitions elements in fixed size ${coll}s.
* @see [[scala.collection.Iterator]], method `grouped`
*
* @param size the number of elements per group
* @return An iterator producing ${coll}s of size `size`, except the
* last will be less than size `size` if the elements don't divide evenly.
*/
def grouped(size: Int): Iterator[C] =
iterator().grouped(size).map(fromSpecificIterable)
/** Groups elements in fixed size blocks by passing a "sliding window"
* over them (as opposed to partitioning them, as is done in `grouped`.)
* The "sliding window" step is set to one.
* @see [[scala.collection.Iterator]], method `sliding`
*
* @param size the number of elements per group
* @return An iterator producing ${coll}s of size `size`, except the
* last element (which may be the only element) will be truncated
* if there are fewer than `size` elements remaining to be grouped.
*/
def sliding(size: Int): Iterator[C] = sliding(size, 1)
/** Groups elements in fixed size blocks by passing a "sliding window"
* over them (as opposed to partitioning them, as is done in grouped.)
* @see [[scala.collection.Iterator]], method `sliding`
*
* @param size the number of elements per group
* @param step the distance between the first elements of successive
* groups
* @return An iterator producing ${coll}s of size `size`, except the
* last element (which may be the only element) will be truncated
* if there are fewer than `size` elements remaining to be grouped.
*/
def sliding(size: Int, step: Int): Iterator[C] =
iterator().sliding(size, step).map(fromSpecificIterable)
/** The rest of the collection without its first element. */
def tail: C = {
if (isEmpty) throw new UnsupportedOperationException
drop(1)
}
/** The initial part of the collection without its last element. */
def init: C = {
if (isEmpty) throw new UnsupportedOperationException
dropRight(1)
}
/** Selects an interval of elements. The returned collection is made up
* of all elements `x` which satisfy the invariant:
* {{{
* from <= indexOf(x) < until
* }}}
* $orderDependent
*
* @param from the lowest index to include from this $coll.
* @param until the lowest index to EXCLUDE from this $coll.
* @return a $coll containing the elements greater than or equal to
* index `from` extending up to (but not including) index `until`
* of this $coll.
*/
def slice(from: Int, until: Int): C =
fromSpecificIterable(View.Drop(View.Take(toIterable, until), from))
/** Partitions this $coll into a map of ${coll}s according to some discriminator function.
*
* Note: When applied to a view or a lazy collection it will always force the elements.
*
* @param f the discriminator function.
* @tparam K the type of keys returned by the discriminator function.
* @return A map from keys to ${coll}s such that the following invariant holds:
* {{{
* (xs groupBy f)(k) = xs filter (x => f(x) == k)
* }}}
* That is, every key `k` is bound to a $coll of those elements `x`
* for which `f(x)` equals `k`.
*
*/
def groupBy[K](f: A => K): immutable.Map[K, C] = {
val m = mutable.Map.empty[K, Builder[A, C]]
val it = iterator()
while (it.hasNext) {
val elem = it.next()
val key = f(elem)
val bldr = m.getOrElseUpdate(key, newSpecificBuilder())
bldr += elem
}
var result = immutable.HashMap.empty[K, C]
val mapIt = m.iterator()
while (mapIt.hasNext) {
val (k, v) = mapIt.next()
result = result.updated(k, v.result())
}
result
}
/**
* Partitions this $coll into a map of ${coll}s according to a discriminator function `key`.
* Each element in a group is transformed into a value of type `B` using the `value` function.
*
* It is equivalent to `groupBy(key).mapValues(_.map(f))`, but more efficient.
*
* {{{
* case class User(name: String, age: Int)
*
* def namesByAge(users: Seq[User]): Map[Int, Seq[String]] =
* users.groupMap(_.age)(_.name)
* }}}
*
* @param key the discriminator function
* @param f the element transformation function
* @tparam K the type of keys returned by the discriminator function
* @tparam B the type of values returned by the transformation function
*/
def groupMap[K, B](key: A => K)(f: A => B): immutable.Map[K, CC[B]] = {
val m = mutable.Map.empty[K, Builder[B, CC[B]]]
for (elem <- this) {
val k = key(elem)
val bldr = m.getOrElseUpdate(k, iterableFactory.newBuilder[B]())
bldr += f(elem)
}
var result = immutable.Map.empty[K, CC[B]]
m.foreach { case (k, v) =>
result = result + ((k, v.result()))
}
result
}
/**
* Partitions this $coll into a map according to a discriminator function `key`. All the values that
* have the same discriminator are then transformed by the `value` function and then reduced into a
* single value with the `reduce` function.
*
* It is equivalent to `groupBy(key).mapValues(_.map(f).reduce(reduce))`, but more efficient.
*
* {{{
* def occurrences[A](as: Seq[A]): Map[A, Int] =
* as.groupMapReduce(identity)(_ => 1)(_ + _)
* }}}
*/
def groupMapReduce[K, B](key: A => K)(f: A => B)(reduce: (B, B) => B): immutable.Map[K, B] = {
val m = mutable.Map.empty[K, B]
for (elem <- this) {
val k = key(elem)
val v =
m.get(k) match {
case Some(b) => reduce(b, f(elem))
case None => f(elem)
}
m.put(k, v)