-
Notifications
You must be signed in to change notification settings - Fork 600
/
Stream.scala
3476 lines (3173 loc) · 132 KB
/
Stream.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 fs2
import cats.data.NonEmptyList
import scala.collection.generic.CanBuildFrom
import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
import cats._
import cats.effect._
import cats.implicits.{catsSyntaxEither => _, _}
import fs2.async.Promise
import fs2.internal._
/**
* A stream producing output of type `O` and which may evaluate `F`
* effects. If `F` is [[Pure]], the stream evaluates no effects.
*
* Much of the API of `Stream` is defined in [[Stream.InvariantOps]].
*
* Laws (using infix syntax):
*
* `append` forms a monoid in conjunction with `empty`:
* - `empty append s == s` and `s append empty == s`.
* - `(s1 append s2) append s3 == s1 append (s2 append s3)`
*
* And `cons` is consistent with using `++` to prepend a single segment:
* - `s.cons(seg) == Stream.segment(seg) ++ s`
*
* `Stream.raiseError` propagates until being caught by `handleErrorWith`:
* - `Stream.raiseError(e) handleErrorWith h == h(e)`
* - `Stream.raiseError(e) ++ s == Stream.raiseError(e)`
* - `Stream.raiseError(e) flatMap f == Stream.raiseError(e)`
*
* `Stream` forms a monad with `emit` and `flatMap`:
* - `Stream.emit >=> f == f` (left identity)
* - `f >=> Stream.emit === f` (right identity - note weaker equality notion here)
* - `(f >=> g) >=> h == f >=> (g >=> h)` (associativity)
* where `Stream.emit(a)` is defined as `segment(Segment.singleton(a)) and
* `f >=> g` is defined as `a => a flatMap f flatMap g`
*
* The monad is the list-style sequencing monad:
* - `(a ++ b) flatMap f == (a flatMap f) ++ (b flatMap f)`
* - `Stream.empty flatMap f == Stream.empty`
*
* '''Technical notes'''
*
* ''Note:'' since the segment structure of the stream is observable, and
* `s flatMap Stream.emit` produces a stream of singleton segments,
* the right identity law uses a weaker notion of equality, `===` which
* normalizes both sides with respect to segment structure:
*
* `(s1 === s2) = normalize(s1) == normalize(s2)`
* where `==` is full equality
* (`a == b` iff `f(a)` is identical to `f(b)` for all `f`)
*
* `normalize(s)` can be defined as `s.flatMap(Stream.emit)`, which just
* produces a singly-chunked stream from any input stream `s`.
*
* ''Note:'' For efficiency `[[Stream.map]]` function operates on an entire
* segment at a time and preserves segment structure, which differs from
* the `map` derived from the monad (`s map f == s flatMap (f andThen Stream.emit)`)
* which would produce singleton segments. In particular, if `f` throws errors, the
* segmented version will fail on the first ''segment'' with an error, while
* the unsegmented version will fail on the first ''element'' with an error.
* Exceptions in pure code like this are strongly discouraged.
*
*
* @hideImplicitConversion PureOps
* @hideImplicitConversion IdOps
* @hideImplicitConversion EmptyOps
* @hideImplicitConversion covaryPure
*/
final class Stream[+F[_], +O] private (private val free: FreeC[Algebra[Nothing, Nothing, ?], Unit])
extends AnyVal {
private[fs2] def get[F2[x] >: F[x], O2 >: O]: FreeC[Algebra[F2, O2, ?], Unit] =
free.asInstanceOf[FreeC[Algebra[F2, O2, ?], Unit]]
/**
* Returns a stream of `O` values wrapped in `Right` until the first error, which is emitted wrapped in `Left`.
*
* @example {{{
* scala> (Stream(1,2,3) ++ Stream.raiseError(new RuntimeException) ++ Stream(4,5,6)).attempt.toList
* res0: List[Either[Throwable,Int]] = List(Right(1), Right(2), Right(3), Left(java.lang.RuntimeException))
* }}}
*
* [[rethrow]] is the inverse of `attempt`, with the caveat that anything after the first failure is discarded.
*/
def attempt: Stream[F, Either[Throwable, O]] =
map(Right(_): Either[Throwable, O]).handleErrorWith(e => Stream.emit(Left(e)))
/**
* Alias for `_.map(_ => o2)`.
*
* @example {{{
* scala> Stream(1,2,3).as(0).toList
* res0: List[Int] = List(0, 0, 0)
* }}}
*/
def as[O2](o2: O2): Stream[F, O2] = map(_ => o2)
/**
* Behaves like the identity function, but requests `n` elements at a time from the input.
*
* @example {{{
* scala> import cats.effect.IO
* scala> val buf = new scala.collection.mutable.ListBuffer[String]()
* scala> Stream.range(0, 100).covary[IO].
* | evalMap(i => IO { buf += s">$i"; i }).
* | buffer(4).
* | evalMap(i => IO { buf += s"<$i"; i }).
* | take(10).
* | compile.toVector.unsafeRunSync
* res0: Vector[Int] = Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
* scala> buf.toList
* res1: List[String] = List(>0, >1, >2, >3, <0, <1, <2, <3, >4, >5, >6, >7, <4, <5, <6, <7, >8, >9, >10, >11, <8, <9)
* }}}
*/
def buffer(n: Int): Stream[F, O] =
this.repeatPull {
_.unconsN(n, allowFewer = true).flatMap {
case Some((hd, tl)) => Pull.output(hd).as(Some(tl))
case None => Pull.pure(None)
}
}
/**
* Behaves like the identity stream, but emits no output until the source is exhausted.
*
* @example {{{
* scala> import cats.effect.IO
* scala> val buf = new scala.collection.mutable.ListBuffer[String]()
* scala> Stream.range(0, 10).covary[IO].
* | evalMap(i => IO { buf += s">$i"; i }).
* | bufferAll.
* | evalMap(i => IO { buf += s"<$i"; i }).
* | take(4).
* | compile.toVector.unsafeRunSync
* res0: Vector[Int] = Vector(0, 1, 2, 3)
* scala> buf.toList
* res1: List[String] = List(>0, >1, >2, >3, >4, >5, >6, >7, >8, >9, <0, <1, <2, <3)
* }}}
*/
def bufferAll: Stream[F, O] = bufferBy(_ => true)
/**
* Behaves like the identity stream, but requests elements from its
* input in blocks that end whenever the predicate switches from true to false.
*
* @example {{{
* scala> import cats.effect.IO
* scala> val buf = new scala.collection.mutable.ListBuffer[String]()
* scala> Stream.range(0, 10).covary[IO].
* | evalMap(i => IO { buf += s">$i"; i }).
* | bufferBy(_ % 2 == 0).
* | evalMap(i => IO { buf += s"<$i"; i }).
* | compile.toVector.unsafeRunSync
* res0: Vector[Int] = Vector(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
* scala> buf.toList
* res1: List[String] = List(>0, >1, <0, <1, >2, >3, <2, <3, >4, >5, <4, <5, >6, >7, <6, <7, >8, >9, <8, <9)
* }}}
*/
def bufferBy(f: O => Boolean): Stream[F, O] = {
def go(buffer: Catenable[Segment[O, Unit]], last: Boolean, s: Stream[F, O]): Pull[F, O, Unit] =
s.pull.unconsChunk.flatMap {
case Some((hd, tl)) =>
val (out, buf, newLast) = {
hd.foldLeft((Catenable.empty: Catenable[Chunk[O]], Vector.empty[O], last)) {
case ((out, buf, last), i) =>
val cur = f(i)
if (!cur && last)
(out :+ Chunk.vector(buf :+ i), Vector.empty, cur)
else (out, buf :+ i, cur)
}
}
if (out.isEmpty) {
go(buffer :+ Segment.vector(buf), newLast, tl)
} else {
Pull.output(Segment.catenated(buffer ++ out.map(Segment.chunk))) >> go(
Catenable.singleton(Segment.vector(buf)),
newLast,
tl)
}
case None => Pull.output(Segment.catenated(buffer))
}
go(Catenable.empty, false, this).stream
}
/**
* Emits only elements that are distinct from their immediate predecessors
* according to `f`, using natural equality for comparison.
*
* Note that `f` is called for each element in the stream multiple times
* and hence should be fast (e.g., an accessor). It is not intended to be
* used for computationally intensive conversions. For such conversions,
* consider something like: `src.map(o => (o, f(o))).changesBy(_._2).map(_._1)`
*
* @example {{{
* scala> import cats.implicits._
* scala> Stream(1,1,2,4,6,9).changesBy(_ % 2).toList
* res0: List[Int] = List(1, 2, 9)
* }}}
*/
def changesBy[O2](f: O => O2)(implicit eq: Eq[O2]): Stream[F, O] =
filterWithPrevious((o1, o2) => eq.neqv(f(o1), f(o2)))
/**
* Outputs all chunks from the source stream.
*
* @example {{{
* scala> (Stream(1) ++ Stream(2, 3) ++ Stream(4, 5, 6)).chunks.toList
* res0: List[Chunk[Int]] = List(Chunk(1), Chunk(2, 3), Chunk(4, 5, 6))
* }}}
*/
def chunks: Stream[F, Chunk[O]] =
this.repeatPull(_.unconsChunk.flatMap {
case None => Pull.pure(None)
case Some((hd, tl)) => Pull.output1(hd).as(Some(tl))
})
/**
* Outputs chunk with a limited maximum size, splitting as necessary.
*
* @example {{{
* scala> (Stream(1) ++ Stream(2, 3) ++ Stream(4, 5, 6)).chunkLimit(2).toList
* res0: List[Chunk[Int]] = List(Chunk(1), Chunk(2, 3), Chunk(4, 5), Chunk(6))
* }}}
*/
def chunkLimit(n: Int): Stream[F, Chunk[O]] =
this.repeatPull {
_.unconsLimit(n).flatMap {
case None => Pull.pure(None)
case Some((hd, tl)) => Pull.output1(hd.force.toChunk).as(Some(tl))
}
}
/**
* Filters and maps simultaneously. Calls `collect` on each segment in the stream.
*
* @example {{{
* scala> Stream(Some(1), Some(2), None, Some(3), None, Some(4)).collect { case Some(i) => i }.toList
* res0: List[Int] = List(1, 2, 3, 4)
* }}}
*/
def collect[O2](pf: PartialFunction[O, O2]): Stream[F, O2] =
mapSegments(_.collect(pf))
/**
* Emits the first element of the stream for which the partial function is defined.
*
* @example {{{
* scala> Stream(None, Some(1), Some(2), None, Some(3)).collectFirst { case Some(i) => i }.toList
* res0: List[Int] = List(1)
* }}}
*/
def collectFirst[O2](pf: PartialFunction[O, O2]): Stream[F, O2] =
this.pull
.find(pf.isDefinedAt)
.flatMap {
case None => Pull.pure(None)
case Some((hd, tl)) => Pull.output1(pf(hd)).as(None)
}
.stream
/**
* Prepends a segment onto the front of this stream.
*
* @example {{{
* scala> Stream(1,2,3).cons(Segment.vector(Vector(-1, 0))).toList
* res0: List[Int] = List(-1, 0, 1, 2, 3)
* }}}
*/
def cons[O2 >: O](s: Segment[O2, Unit]): Stream[F, O2] =
Stream.segment(s) ++ this
/**
* Prepends a chunk onto the front of this stream.
*
* @example {{{
* scala> Stream(1,2,3).consChunk(Chunk.vector(Vector(-1, 0))).toList
* res0: List[Int] = List(-1, 0, 1, 2, 3)
* }}}
*/
def consChunk[O2 >: O](c: Chunk[O2]): Stream[F, O2] =
if (c.isEmpty) this else Stream.chunk(c) ++ this
/**
* Prepends a single value onto the front of this stream.
*
* @example {{{
* scala> Stream(1,2,3).cons1(0).toList
* res0: List[Int] = List(0, 1, 2, 3)
* }}}
*/
def cons1[O2 >: O](o: O2): Stream[F, O2] =
cons(Segment.singleton(o))
/**
* Lifts this stream to the specified output type.
*
* @example {{{
* scala> Stream(Some(1), Some(2), Some(3)).covaryOutput[Option[Int]]
* res0: Stream[Pure,Option[Int]] = Stream(..)
* }}}
*/
def covaryOutput[O2 >: O]: Stream[F, O2] = this.asInstanceOf[Stream[F, O2]]
/**
* Skips the first element that matches the predicate.
*
* @example {{{
* scala> Stream.range(1, 10).delete(_ % 2 == 0).toList
* res0: List[Int] = List(1, 3, 4, 5, 6, 7, 8, 9)
* }}}
*/
def delete(p: O => Boolean): Stream[F, O] =
this.pull
.takeWhile(o => !p(o))
.flatMap {
case None => Pull.pure(None)
case Some(s) => s.drop(1).pull.echo
}
.stream
/**
* Removes all output values from this stream.
*
* Often used with `merge` to run one side of the merge for its effect
* while getting outputs from the opposite side of the merge.
*
* @example {{{
* scala> import cats.effect.IO
* scala> Stream.eval(IO(println("x"))).drain.compile.toVector.unsafeRunSync
* res0: Vector[Nothing] = Vector()
* }}}
*/
def drain: Stream[F, Nothing] = this.mapSegments(_ => Segment.empty)
/**
* Drops `n` elements of the input, then echoes the rest.
*
* @example {{{
* scala> Stream.range(0,10).drop(5).toList
* res0: List[Int] = List(5, 6, 7, 8, 9)
* }}}
*/
def drop(n: Long): Stream[F, O] =
this.pull.drop(n).flatMap(_.map(_.pull.echo).getOrElse(Pull.done)).stream
/**
* Drops the last element.
*
* @example {{{
* scala> Stream.range(0,10).dropLast.toList
* res0: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8)
* }}}
*/
def dropLast: Stream[F, O] = dropLastIf(_ => true)
/**
* Drops the last element if the predicate evaluates to true.
*
* @example {{{
* scala> Stream.range(0,10).dropLastIf(_ > 5).toList
* res0: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8)
* }}}
*/
def dropLastIf(p: O => Boolean): Stream[F, O] = {
def go(last: Chunk[O], s: Stream[F, O]): Pull[F, O, Unit] =
s.pull.unconsChunk.flatMap {
case Some((hd, tl)) =>
if (hd.nonEmpty) Pull.outputChunk(last) >> go(hd, tl)
else go(last, tl)
case None =>
val o = last(last.size - 1)
if (p(o)) {
val (prefix, _) = last.splitAt(last.size - 1)
Pull.outputChunk(prefix)
} else Pull.outputChunk(last)
}
def unconsNonEmptyChunk(s: Stream[F, O]): Pull[F, Nothing, Option[(Chunk[O], Stream[F, O])]] =
s.pull.unconsChunk.flatMap {
case Some((hd, tl)) =>
if (hd.nonEmpty) Pull.pure(Some((hd, tl)))
else unconsNonEmptyChunk(tl)
case None => Pull.pure(None)
}
unconsNonEmptyChunk(this).flatMap {
case Some((hd, tl)) => go(hd, tl)
case None => Pull.done
}.stream
}
/**
* Outputs all but the last `n` elements of the input.
*
* @example {{{
* scala> Stream.range(0,10).dropRight(5).toList
* res0: List[Int] = List(0, 1, 2, 3, 4)
* }}}
*/
def dropRight(n: Int): Stream[F, O] =
if (n <= 0) this
else {
def go(acc: Vector[O], s: Stream[F, O]): Pull[F, O, Option[Unit]] =
s.pull.uncons.flatMap {
case None => Pull.pure(None)
case Some((hd, tl)) =>
val all = acc ++ hd.force.toVector
Pull.output(Segment.vector(all.dropRight(n))) >> go(all.takeRight(n), tl)
}
go(Vector.empty, this).stream
}
/**
* Like [[dropWhile]], but drops the first value which tests false.
*
* @example {{{
* scala> Stream.range(0,10).dropThrough(_ != 4).toList
* res0: List[Int] = List(5, 6, 7, 8, 9)
* }}}
*/
def dropThrough(p: O => Boolean): Stream[F, O] =
this.pull
.dropThrough(p)
.flatMap(_.map(_.pull.echo).getOrElse(Pull.done))
.stream
/**
* Drops elements from the head of this stream until the supplied predicate returns false.
*
* @example {{{
* scala> Stream.range(0,10).dropWhile(_ != 4).toList
* res0: List[Int] = List(4, 5, 6, 7, 8, 9)
* }}}
*/
def dropWhile(p: O => Boolean): Stream[F, O] =
this.pull
.dropWhile(p)
.flatMap(_.map(_.pull.echo).getOrElse(Pull.done))
.stream
/**
* Emits `true` as soon as a matching element is received, else `false` if no input matches.
*
* @example {{{
* scala> Stream.range(0,10).exists(_ == 4).toList
* res0: List[Boolean] = List(true)
* scala> Stream.range(0,10).exists(_ == 10).toList
* res1: List[Boolean] = List(false)
* }}}
*/
def exists(p: O => Boolean): Stream[F, Boolean] =
this.pull.forall(!p(_)).flatMap(r => Pull.output1(!r)).stream
/**
* Emits only inputs which match the supplied predicate.
*
* @example {{{
* scala> Stream.range(0,10).filter(_ % 2 == 0).toList
* res0: List[Int] = List(0, 2, 4, 6, 8)
* }}}
*/
def filter(p: O => Boolean): Stream[F, O] = mapSegments(_.filter(p))
/**
* Like `filter`, but the predicate `f` depends on the previously emitted and
* current elements.
*
* @example {{{
* scala> Stream(1, -1, 2, -2, 3, -3, 4, -4).filterWithPrevious((previous, current) => previous < current).toList
* res0: List[Int] = List(1, 2, 3, 4)
* }}}
*/
def filterWithPrevious(f: (O, O) => Boolean): Stream[F, O] = {
def go(last: O, s: Stream[F, O]): Pull[F, O, Option[Unit]] =
s.pull.uncons.flatMap {
case None => Pull.pure(None)
case Some((hd, tl)) =>
// Check if we can emit this chunk unmodified
Pull
.segment(
hd.fold((true, last)) {
case ((acc, last), o) => (acc && f(last, o), o)
}
.mapResult(_._2))
.flatMap {
case (allPass, newLast) =>
if (allPass) {
Pull.output(hd) >> go(newLast, tl)
} else {
Pull
.segment(hd
.fold((Vector.empty[O], last)) {
case ((acc, last), o) =>
if (f(last, o)) (acc :+ o, o)
else (acc, last)
}
.mapResult(_._2))
.flatMap {
case (acc, newLast) =>
Pull.output(Segment.vector(acc)) >> go(newLast, tl)
}
}
}
}
this.pull.uncons1.flatMap {
case None => Pull.pure(None)
case Some((hd, tl)) => Pull.output1(hd) >> go(hd, tl)
}.stream
}
/**
* Emits the first input (if any) which matches the supplied predicate.
*
* @example {{{
* scala> Stream.range(1,10).find(_ % 2 == 0).toList
* res0: List[Int] = List(2)
* }}}
*/
def find(f: O => Boolean): Stream[F, O] =
this.pull
.find(f)
.flatMap {
_.map { case (hd, tl) => Pull.output1(hd) }.getOrElse(Pull.done)
}
.stream
/**
* Folds all inputs using an initial value `z` and supplied binary operator,
* and emits a single element stream.
*
* @example {{{
* scala> Stream(1, 2, 3, 4, 5).fold(0)(_ + _).toList
* res0: List[Int] = List(15)
* }}}
*/
def fold[O2](z: O2)(f: (O2, O) => O2): Stream[F, O2] =
this.pull.fold(z)(f).flatMap(Pull.output1).stream
/**
* Folds all inputs using the supplied binary operator, and emits a single-element
* stream, or the empty stream if the input is empty.
*
* @example {{{
* scala> Stream(1, 2, 3, 4, 5).fold1(_ + _).toList
* res0: List[Int] = List(15)
* }}}
*/
def fold1[O2 >: O](f: (O2, O2) => O2): Stream[F, O2] =
this.pull.fold1(f).flatMap(_.map(Pull.output1).getOrElse(Pull.done)).stream
/**
* Alias for `map(f).foldMonoid`.
*
* @example {{{
* scala> import cats.implicits._
* scala> Stream(1, 2, 3, 4, 5).foldMap(_ => 1).toList
* res0: List[Int] = List(5)
* }}}
*/
def foldMap[O2](f: O => O2)(implicit O2: Monoid[O2]): Stream[F, O2] =
fold(O2.empty)((acc, o) => O2.combine(acc, f(o)))
/**
* Emits a single `true` value if all input matches the predicate.
* Halts with `false` as soon as a non-matching element is received.
*
* @example {{{
* scala> Stream(1, 2, 3, 4, 5).forall(_ < 10).toList
* res0: List[Boolean] = List(true)
* }}}
*/
def forall(p: O => Boolean): Stream[F, Boolean] =
this.pull.forall(p).flatMap(Pull.output1).stream
/**
* Partitions the input into a stream of segments according to a discriminator function.
*
* Each chunk in the source stream is grouped using the supplied discriminator function
* and the results of the grouping are emitted each time the discriminator function changes
* values.
*
* @example {{{
* scala> import cats.implicits._
* scala> Stream("Hello", "Hi", "Greetings", "Hey").groupAdjacentBy(_.head).toList.map { case (k,vs) => k -> vs.force.toList }
* res0: List[(Char,List[String])] = List((H,List(Hello, Hi)), (G,List(Greetings)), (H,List(Hey)))
* }}}
*/
def groupAdjacentBy[O2](f: O => O2)(implicit eq: Eq[O2]): Stream[F, (O2, Segment[O, Unit])] = {
def go(current: Option[(O2, Segment[O, Unit])],
s: Stream[F, O]): Pull[F, (O2, Segment[O, Unit]), Unit] =
s.pull.unconsChunk.flatMap {
case Some((hd, tl)) =>
if (hd.nonEmpty) {
val (k1, out) = current.getOrElse((f(hd(0)), Segment.empty[O]))
doChunk(hd, tl, k1, out, None)
} else {
go(current, tl)
}
case None =>
val l = current
.map { case (k1, out) => Pull.output1((k1, out)) }
.getOrElse(Pull
.pure(()))
l >> Pull.done
}
@annotation.tailrec
def doChunk(chunk: Chunk[O],
s: Stream[F, O],
k1: O2,
out: Segment[O, Unit],
acc: Option[Segment[(O2, Segment[O, Unit]), Unit]])
: Pull[F, (O2, Segment[O, Unit]), Unit] = {
val differsAt = chunk.indexWhere(v => eq.neqv(f(v), k1)).getOrElse(-1)
if (differsAt == -1) {
// whole chunk matches the current key, add this chunk to the accumulated output
val newOut: Segment[O, Unit] = out ++ Segment.chunk(chunk)
acc match {
case None => go(Some((k1, newOut)), s)
case Some(acc) =>
// potentially outputs one additional chunk (by splitting the last one in two)
Pull.output(acc) >> go(Some((k1, newOut)), s)
}
} else {
// at least part of this chunk does not match the current key, need to group and retain chunkiness
// split the chunk into the bit where the keys match and the bit where they don't
val matching = Segment.chunk(chunk).take(differsAt)
val newOut: Segment[O, Unit] = out ++ matching.voidResult
val nonMatching = chunk.drop(differsAt)
// nonMatching is guaranteed to be non-empty here, because we know the last element of the chunk doesn't have
// the same key as the first
val k2 = f(nonMatching(0))
doChunk(nonMatching,
s,
k2,
Segment.empty[O],
Some(acc.getOrElse(Segment.empty) ++ Segment((k1, newOut))))
}
}
go(None, this).stream
}
/**
* Emits the first element of this stream (if non-empty) and then halts.
*
* @example {{{
* scala> Stream(1, 2, 3).head.toList
* res0: List[Int] = List(1)
* }}}
*/
def head: Stream[F, O] = take(1)
/**
* Emits the specified separator between every pair of elements in the source stream.
*
* @example {{{
* scala> Stream(1, 2, 3, 4, 5).intersperse(0).toList
* res0: List[Int] = List(1, 0, 2, 0, 3, 0, 4, 0, 5)
* }}}
*/
def intersperse[O2 >: O](separator: O2): Stream[F, O2] =
this.pull.echo1.flatMap {
case None => Pull.pure(None)
case Some(s) =>
s.repeatPull {
_.uncons.flatMap {
case None => Pull.pure(None)
case Some((hd, tl)) =>
val interspersed = {
val bldr = Vector.newBuilder[O2]
hd.force.toVector.foreach { o =>
bldr += separator; bldr += o
}
Chunk.vector(bldr.result)
}
Pull.output(Segment.chunk(interspersed)) >> Pull.pure(Some(tl))
}
}
.pull
.echo
}.stream
/**
* Returns the last element of this stream, if non-empty.
*
* @example {{{
* scala> Stream(1, 2, 3).last.toList
* res0: List[Option[Int]] = List(Some(3))
* }}}
*/
def last: Stream[F, Option[O]] =
this.pull.last.flatMap(Pull.output1).stream
/**
* Returns the last element of this stream, if non-empty, otherwise the supplied `fallback` value.
*
* @example {{{
* scala> Stream(1, 2, 3).lastOr(0).toList
* res0: List[Int] = List(3)
* scala> Stream.empty.lastOr(0).toList
* res1: List[Int] = List(0)
* }}}
*/
def lastOr[O2 >: O](fallback: => O2): Stream[F, O2] =
this.pull.last.flatMap {
case Some(o) => Pull.output1(o)
case None => Pull.output1(fallback)
}.stream
/**
* Maps a running total according to `S` and the input with the function `f`.
*
* @example {{{
* scala> Stream("Hello", "World").mapAccumulate(0)((l, s) => (l + s.length, s.head)).toVector
* res0: Vector[(Int, Char)] = Vector((5,H), (10,W))
* }}}
*/
def mapAccumulate[S, O2](init: S)(f: (S, O) => (S, O2)): Stream[F, (S, O2)] = {
val f2 = (s: S, o: O) => {
val (newS, newO) = f(s, o)
(newS, (newS, newO))
}
this.scanSegments(init)((acc, seg) => seg.mapAccumulate(acc)(f2).mapResult(_._2))
}
/**
* Applies the specified pure function to each input and emits the result.
*
* @example {{{
* scala> Stream("Hello", "World!").map(_.size).toList
* res0: List[Int] = List(5, 6)
* }}}
*/
def map[O2](f: O => O2): Stream[F, O2] =
this.repeatPull(_.uncons.flatMap {
case None => Pull.pure(None);
case Some((hd, tl)) => Pull.output(hd.map(f)).as(Some(tl))
})
/**
* Applies the specified pure function to each chunk in this stream.
*
* @example {{{
* scala> Stream(1, 2, 3).append(Stream(4, 5, 6)).mapChunks { c => val ints = c.toInts; for (i <- 0 until ints.values.size) ints.values(i) = 0; ints.toSegment }.toList
* res0: List[Int] = List(0, 0, 0, 0, 0, 0)
* }}}
*/
def mapChunks[O2](f: Chunk[O] => Segment[O2, Unit]): Stream[F, O2] =
this.repeatPull {
_.unconsChunk.flatMap {
case None => Pull.pure(None);
case Some((hd, tl)) => Pull.output(f(hd)).as(Some(tl))
}
}
/**
* Applies the specified pure function to each segment in this stream.
*
* @example {{{
* scala> (Stream.range(1,5) ++ Stream.range(5,10)).mapSegments(s => s.scan(0)(_ + _).voidResult).toList
* res0: List[Int] = List(0, 1, 3, 6, 10, 0, 5, 11, 18, 26, 35)
* }}}
*/
def mapSegments[O2](f: Segment[O, Unit] => Segment[O2, Unit]): Stream[F, O2] =
this.repeatPull {
_.uncons.flatMap {
case None => Pull.pure(None);
case Some((hd, tl)) => Pull.output(f(hd)).as(Some(tl))
}
}
/**
* Behaves like the identity function but halts the stream on an error and does not return the error.
*
* @example {{{
* scala> (Stream(1,2,3) ++ Stream.raiseError(new RuntimeException) ++ Stream(4, 5, 6)).mask.toList
* res0: List[Int] = List(1, 2, 3)
* }}}
*/
def mask: Stream[F, O] = this.handleErrorWith(_ => Stream.empty)
/**
* Emits each output wrapped in a `Some` and emits a `None` at the end of the stream.
*
* `s.noneTerminate.unNoneTerminate == s`
*
* @example {{{
* scala> Stream(1,2,3).noneTerminate.toList
* res0: List[Option[Int]] = List(Some(1), Some(2), Some(3), None)
* }}}
*/
def noneTerminate: Stream[F, Option[O]] = map(Some(_)) ++ Stream.emit(None)
/**
* Repeat this stream an infinite number of times.
*
* `s.repeat == s ++ s ++ s ++ ...`
*
* @example {{{
* scala> Stream(1,2,3).repeat.take(8).toList
* res0: List[Int] = List(1, 2, 3, 1, 2, 3, 1, 2)
* }}}
*/
def repeat: Stream[F, O] =
this ++ repeat
/**
* Converts a `Stream[F,Either[Throwable,O]]` to a `Stream[F,O]`, which emits right values and fails upon the first `Left(t)`.
* Preserves chunkiness.
*
* @example {{{
* scala> Stream(Right(1), Right(2), Left(new RuntimeException), Right(3)).rethrow.handleErrorWith(t => Stream(-1)).toList
* res0: List[Int] = List(-1)
* }}}
*/
def rethrow[O2](implicit ev: O <:< Either[Throwable, O2]): Stream[F, O2] = {
val _ = ev // Convince scalac that ev is used
this.asInstanceOf[Stream[F, Either[Throwable, O2]]].segments.flatMap { s =>
val errs = s.collect { case Left(e) => e }
errs.force.uncons1 match {
case Left(()) => Stream.segment(s.collect { case Right(i) => i })
case Right((hd, tl)) => Stream.raiseError(hd)
}
}
}
/** Alias for [[fold1]]. */
def reduce[O2 >: O](f: (O2, O2) => O2): Stream[F, O2] = fold1(f)
/**
* Left fold which outputs all intermediate results.
*
* @example {{{
* scala> Stream(1,2,3,4).scan(0)(_ + _).toList
* res0: List[Int] = List(0, 1, 3, 6, 10)
* }}}
*
* More generally:
* `Stream().scan(z)(f) == Stream(z)`
* `Stream(x1).scan(z)(f) == Stream(z, f(z,x1))`
* `Stream(x1,x2).scan(z)(f) == Stream(z, f(z,x1), f(f(z,x1),x2))`
* etc
*/
def scan[O2](z: O2)(f: (O2, O) => O2): Stream[F, O2] =
(Pull.output1(z) >> scan_(z)(f)).stream
private def scan_[O2](z: O2)(f: (O2, O) => O2): Pull[F, O2, Unit] =
this.pull.uncons.flatMap {
case None => Pull.done
case Some((hd, tl)) =>
hd.scan(z)(f).mapResult(_._2).force.uncons1 match {
case Left(acc) => tl.scan_(acc)(f)
case Right((_, out)) =>
Pull.segment(out).flatMap { acc =>
tl.scan_(acc)(f)
}
}
}
/**
* Like `[[scan]]`, but uses the first element of the stream as the seed.
*
* @example {{{
* scala> Stream(1,2,3,4).scan1(_ + _).toList
* res0: List[Int] = List(1, 3, 6, 10)
* }}}
*/
def scan1[O2 >: O](f: (O2, O2) => O2): Stream[F, O2] =
this.pull.uncons1.flatMap {
case None => Pull.done
case Some((hd, tl)) => Pull.output1(hd) >> tl.scan_(hd: O2)(f)
}.stream
/**
* Scopes are typically inserted automatically, at the boundary of a pull (i.e., when a pull
* is converted to a stream). This method allows a scope to be explicitly demarcated so that
* resources can be freed earlier than when using automatically inserted scopes. This is
* useful when using `streamNoScope` to convert from `Pull` to `Stream` -- i.e., by choosing
* to *not* have scopes inserted automatically, you may end up needing to demarcate scopes
* manually at a higher level in the stream structure.
*
* Note: see the disclaimer about the use of `streamNoScope`.
*/
def scope: Stream[F, O] = Stream.fromFreeC(Algebra.scope(get))
/**
* Outputs the segments of this stream as output values, ensuring each segment has maximum size `n`, splitting segments as necessary.
*
* @example {{{
* scala> Stream(1,2,3).repeat.segmentLimit(2).take(5).toList
* res0: List[Segment[Int,Unit]] = List(Chunk(1, 2), Chunk(3), Chunk(1, 2), Chunk(3), Chunk(1, 2))
* }}}
*/
def segmentLimit(n: Int): Stream[F, Segment[O, Unit]] =
this.repeatPull {
_.unconsLimit(n).flatMap {
case Some((hd, tl)) => Pull.output1(hd).as(Some(tl))
case None => Pull.pure(None)
}
}
/**
* Outputs segments of size `n`.
*
* Segments from the source stream are split as necessary.
* If `allowFewer` is true, the last segment that is emitted may have less than `n` elements.
*
* @example {{{
* scala> Stream(1,2,3).repeat.segmentN(2).take(5).toList
* res0: List[Segment[Int,Unit]] = List(Chunk(1, 2), catenated(Chunk(3), Chunk(1)), Chunk(2, 3), Chunk(1, 2), catenated(Chunk(3), Chunk(1)))
* }}}
*/
def segmentN(n: Int, allowFewer: Boolean = true): Stream[F, Segment[O, Unit]] =
this.repeatPull {
_.unconsN(n, allowFewer).flatMap {
case Some((hd, tl)) => Pull.output1(hd).as(Some(tl))
case None => Pull.pure(None)
}
}
/**
* Outputs all segments from the source stream.
*
* @example {{{
* scala> Stream(1,2,3).repeat.segments.take(5).toList
* res0: List[Segment[Int,Unit]] = List(Chunk(1, 2, 3), Chunk(1, 2, 3), Chunk(1, 2, 3), Chunk(1, 2, 3), Chunk(1, 2, 3))
* }}}
*/
def segments: Stream[F, Segment[O, Unit]] =
this.repeatPull(_.uncons.flatMap {
case None => Pull.pure(None);
case Some((hd, tl)) => Pull.output1(hd).as(Some(tl))
})
/**
* Groups inputs in fixed size chunks by passing a "sliding window"
* of size `n` over them. If the input contains less than or equal to
* `n` elements, only one chunk of this size will be emitted.
*
* @example {{{
* scala> Stream(1, 2, 3, 4).sliding(2).toList
* res0: List[scala.collection.immutable.Queue[Int]] = List(Queue(1, 2), Queue(2, 3), Queue(3, 4))
* }}}
* @throws scala.IllegalArgumentException if `n` <= 0
*/
def sliding(n: Int): Stream[F, collection.immutable.Queue[O]] = {
require(n > 0, "n must be > 0")
def go(window: collection.immutable.Queue[O],
s: Stream[F, O]): Pull[F, collection.immutable.Queue[O], Unit] =
s.pull.uncons.flatMap {
case None => Pull.done
case Some((hd, tl)) =>
hd.scan(window)((w, i) => w.dequeue._2.enqueue(i))
.mapResult(_._2)
.force
.drop(1) match {
case Left((w2, _)) => go(w2, tl)
case Right(out) =>
Pull.segment(out).flatMap { window =>
go(window, tl)
}
}
}
this.pull
.unconsN(n, true)
.flatMap {
case None => Pull.done
case Some((hd, tl)) =>
val window = hd
.fold(collection.immutable.Queue.empty[O])(_.enqueue(_))
.force
.run
._2
Pull.output1(window) >> go(window, tl)
}
.stream
}
/**
* Breaks the input into chunks where the delimiter matches the predicate.
* The delimiter does not appear in the output. Two adjacent delimiters in the
* input result in an empty chunk in the output.
*
* @example {{{
* scala> Stream.range(0, 10).split(_ % 4 == 0).toList
* res0: List[Segment[Int,Unit]] = List(empty, catenated(Chunk(1), Chunk(2), Chunk(3), empty), catenated(Chunk(5), Chunk(6), Chunk(7), empty), Chunk(9))
* }}}
*/
def split(f: O => Boolean): Stream[F, Segment[O, Unit]] = {
def go(buffer: Catenable[Segment[O, Unit]], s: Stream[F, O]): Pull[F, Segment[O, Unit], Unit] =
s.pull.uncons.flatMap {
case Some((hd, tl)) =>
hd.force.splitWhile(o => !(f(o))) match {
case Left((_, out)) =>
if (out.isEmpty) go(buffer, tl)
else go(buffer ++ out.map(Segment.chunk), tl)