forked from functionaljava/functionaljava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStream.java
More file actions
1808 lines (1652 loc) · 60.1 KB
/
Stream.java
File metadata and controls
1808 lines (1652 loc) · 60.1 KB
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 fj.data;
import fj.Effect;
import fj.Equal;
import fj.F;
import fj.F2;
import fj.F3;
import fj.Function;
import fj.Monoid;
import fj.Ord;
import fj.P;
import fj.P1;
import fj.P2;
import fj.Unit;
import fj.control.parallel.Promise;
import fj.control.parallel.Strategy;
import fj.Ordering;
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import static fj.Bottom.error;
import static fj.Function.compose;
import static fj.Function.constant;
import static fj.Function.curry;
import static fj.Function.flip;
import static fj.Function.identity;
import static fj.P.p;
import static fj.P.p2;
import static fj.Unit.unit;
import static fj.control.parallel.Promise.promise;
import static fj.data.Array.mkArray;
import static fj.data.Option.none;
import static fj.data.Option.some;
import static fj.function.Booleans.not;
import static fj.Ordering.EQ;
import static fj.Ordering.GT;
import static fj.Ordering.LT;
/**
* A lazy (not yet evaluated), immutable, singly linked list.
*
* @version %build.number%
*/
public abstract class Stream<A> implements Iterable<A> {
private Stream() {
}
/**
* Returns an iterator for this stream. This method exists to permit the use in a <code>for</code>-each loop.
*
* @return A iterator for this stream.
*/
public final Iterator<A> iterator() {
return toCollection().iterator();
}
/**
* The first element of the stream or fails for the empty stream.
*
* @return The first element of the stream or fails for the empty stream.
*/
public abstract A head();
/**
* The stream without the first element or fails for the empty stream.
*
* @return The stream without the first element or fails for the empty stream.
*/
public abstract P1<Stream<A>> tail();
/**
* Returns <code>true</code> if this stream is empty, <code>false</code> otherwise.
*
* @return <code>true</code> if this stream is empty, <code>false</code> otherwise.
*/
public final boolean isEmpty() {
return this instanceof Nil;
}
/**
* Returns <code>false</code> if this stream is empty, <code>true</code> otherwise.
*
* @return <code>false</code> if this stream is empty, <code>true</code> otherwise.
*/
public final boolean isNotEmpty() {
return this instanceof Cons;
}
/**
* Performs a reduction on this stream using the given arguments.
*
* @param nil The value to return if this stream is empty.
* @param cons The function to apply to the head and tail of this stream if it is not empty.
* @return A reduction on this stream.
*/
public final <B> B stream(final B nil, final F<A, F<P1<Stream<A>>, B>> cons) {
return isEmpty() ? nil : cons.f(head()).f(tail());
}
/**
* Performs a right-fold reduction across this stream. This function uses O(length) stack space.
*
* @param f The function to apply on each element of the stream.
* @param b The beginning value to start the application from.
* @return The final result after the right-fold reduction.
*/
public final <B> B foldRight(final F<A, F<P1<B>, B>> f, final B b) {
return isEmpty() ? b : f.f(head()).f(new P1<B>() {
public B _1() {
return tail()._1().foldRight(f, b);
}
});
}
/**
* Performs a right-fold reduction across this stream. This function uses O(length) stack space.
*
* @param f The function to apply on each element of the stream.
* @param b The beginning value to start the application from.
* @return The final result after the right-fold reduction.
*/
public final <B> B foldRight(final F2<A, P1<B>, B> f, final B b) {
return foldRight(curry(f), b);
}
/**
* Performs a right-fold reduction across this stream. This function uses O(length) stack space.
*
* @param f The function to apply on each element of the stream.
* @param b The beginning value to start the application from.
* @return The final result after the right-fold reduction.
*/
public final <B> B foldRight1(final F<A, F<B, B>> f, final B b) {
return foldRight(compose(Function.<P1<B>, B, B>andThen().f(P1.<B>__1()), f), b);
}
/**
* Performs a right-fold reduction across this stream. This function uses O(length) stack space.
*
* @param f The function to apply on each element of the stream.
* @param b The beginning value to start the application from.
* @return The final result after the right-fold reduction.
*/
public final <B> B foldRight1(final F2<A, B, B> f, final B b) {
return foldRight1(curry(f), b);
}
/**
* Performs a left-fold reduction across this stream. This function runs in constant space.
*
* @param f The function to apply on each element of the stream.
* @param b The beginning value to start the application from.
* @return The final result after the left-fold reduction.
*/
public final <B> B foldLeft(final F<B, F<A, B>> f, final B b) {
B x = b;
for (Stream<A> xs = this; !xs.isEmpty(); xs = xs.tail()._1())
x = f.f(x).f(xs.head());
return x;
}
/**
* Performs a left-fold reduction across this stream. This function runs in constant space.
*
* @param f The function to apply on each element of the stream.
* @param b The beginning value to start the application from.
* @return The final result after the left-fold reduction.
*/
public final <B> B foldLeft(final F2<B, A, B> f, final B b) {
return foldLeft(curry(f), b);
}
/**
* Takes the first 2 elements of the stream and applies the function to them,
* then applies the function to the result and the third element and so on.
*
* @param f The function to apply on each element of the stream.
* @return The final result after the left-fold reduction.
*/
public final A foldLeft1(final F2<A, A, A> f) {
return foldLeft1(curry(f));
}
/**
* Takes the first 2 elements of the stream and applies the function to them,
* then applies the function to the result and the third element and so on.
*
* @param f The function to apply on each element of the stream.
* @return The final result after the left-fold reduction.
*/
public final A foldLeft1(final F<A, F<A, A>> f) {
if (isEmpty())
throw error("Undefined: foldLeft1 on empty list");
return tail()._1().foldLeft(f, head());
}
/**
* Returns the head of this stream if there is one or the given argument if this stream is empty.
*
* @param a The argument to return if this stream is empty.
* @return The head of this stream if there is one or the given argument if this stream is empty.
*/
public final A orHead(final P1<A> a) {
return isEmpty() ? a._1() : head();
}
/**
* Returns the tail of this stream if there is one or the given argument if this stream is empty.
*
* @param as The argument to return if this stream is empty.
* @return The tail of this stream if there is one or the given argument if this stream is empty.
*/
public final P1<Stream<A>> orTail(final P1<Stream<A>> as) {
return isEmpty() ? as : tail();
}
/**
* Intersperses the given value between each two elements of the stream.
*
* @param a The value to intersperse between values of the stream.
* @return A new stream with the given value between each two elements of the stream.
*/
public final Stream<A> intersperse(final A a) {
return isEmpty() ? this : cons(head(), new P1<Stream<A>>() {
public Stream<A> _1() {
return prefix(a, tail()._1());
}
public Stream<A> prefix(final A x, final Stream<A> xs) {
return xs.isEmpty() ? xs : cons(x, p(cons(xs.head(), new P1<Stream<A>>() {
public Stream<A> _1() {
return prefix(a, xs.tail()._1());
}
})));
}
});
}
/**
* Maps the given function across this stream.
*
* @param f The function to map across this stream.
* @return A new stream after the given function has been applied to each element.
*/
public final <B> Stream<B> map(final F<A, B> f) {
return isEmpty() ? Stream.<B>nil() : cons(f.f(head()), new P1<Stream<B>>() {
public Stream<B> _1() {
return tail()._1().map(f);
}
});
}
/**
* Provides a first-class version of the map function.
*
* @return A function that maps a given function across a given stream.
*/
public static <A, B> F<F<A, B>, F<Stream<A>, Stream<B>>> map_() {
return new F<F<A, B>, F<Stream<A>, Stream<B>>>() {
public F<Stream<A>, Stream<B>> f(final F<A, B> f) {
return new F<Stream<A>, Stream<B>>() {
public Stream<B> f(final Stream<A> as) {
return as.map(f);
}
};
}
};
}
/**
* Performs a side-effect for each element of this stream.
*
* @param f The side-effect to perform for the given element.
* @return The unit value.
*/
public final Unit foreach(final F<A, Unit> f) {
for (Stream<A> xs = this; xs.isNotEmpty(); xs = xs.tail()._1())
f.f(xs.head());
return unit();
}
/**
* Performs a side-effect for each element of this stream.
*
* @param f The side-effect to perform for the given element.
*/
public final void foreach(final Effect<A> f) {
for (Stream<A> xs = this; xs.isNotEmpty(); xs = xs.tail()._1())
f.e(xs.head());
}
/**
* Filters elements from this stream by returning only elements which produce <code>true</code>
* when the given function is applied to them.
*
* @param f The predicate function to filter on.
* @return A new stream whose elements all match the given predicate.
*/
public final Stream<A> filter(final F<A, Boolean> f) {
final Stream<A> as = dropWhile(not(f));
return as.isNotEmpty() ? cons(as.head(), new P1<Stream<A>>() {
public Stream<A> _1() {
return as.tail()._1().filter(f);
}
}) : as;
}
/**
* Appends the given stream to this stream.
*
* @param as The stream to append to this one.
* @return A new stream that has appended the given stream.
*/
public final Stream<A> append(final Stream<A> as) {
return isEmpty() ? as : cons(head(), new P1<Stream<A>>() {
public Stream<A> _1() {
return tail()._1().append(as);
}
});
}
/**
* Appends the given stream to this stream.
*
* @param as The stream to append to this one.
* @return A new stream that has appended the given stream.
*/
public final Stream<A> append(final P1<Stream<A>> as) {
return isEmpty() ? as._1() : cons(head(), new P1<Stream<A>>() {
public Stream<A> _1() {
return tail()._1().append(as);
}
});
}
/**
* Returns a new stream of all the items in this stream that do not appear in the given stream.
*
* @param eq an equality for the items of the streams.
* @param xs a list to subtract from this stream.
* @return a stream of all the items in this stream that do not appear in the given stream.
*/
public final Stream<A> minus(final Equal<A> eq, final Stream<A> xs) {
return removeAll(compose(Monoid.disjunctionMonoid.sumLeftS(), xs.mapM(curry(eq.eq()))));
}
/**
* Filters elements from this stream by returning only elements which produce <code>false</code> when
* the given function is applied to them.
*
* @param f The predicate function to filter on.
* @return A new stream whose elements do not match the given predicate.
*/
public final Stream<A> removeAll(final F<A, Boolean> f) {
return filter(compose(not, f));
}
/**
* Turn a stream of functions into a function returning a stream.
*
* @param fs The stream of functions to sequence into a single function that returns a stream.
* @return A function that, when given an argument, applies all the functions in the given stream to it
* and returns a stream of the results.
*/
public static <A, B> F<B, Stream<A>> sequence_(final Stream<F<B, A>> fs) {
return fs.foldRight(new F2<F<B, A>, P1<F<B, Stream<A>>>, F<B, Stream<A>>>() {
public F<B, Stream<A>> f(final F<B, A> baf, final P1<F<B, Stream<A>>> p1) {
return Function.bind(baf, p1._1(), Function.curry(new F2<A, Stream<A>, Stream<A>>() {
public Stream<A> f(final A a, final Stream<A> stream) {
return cons(a, p(stream));
}
}));
}
}, Function
.<B, Stream<A>>constant(Stream.<A>nil()));
}
/**
* Maps the given function of arity-2 across this stream and returns a function that applies all the resulting
* functions to a given argument.
*
* @param f A function of arity-2
* @return A function that, when given an argument, applies the given function to that argument and every element
* in this list.
*/
public final <B, C> F<B, Stream<C>> mapM(final F<A, F<B, C>> f) {
return sequence_(map(f));
}
/**
* Binds the given function across each element of this stream with a final join.
*
* @param f The function to apply to each element of this stream.
* @return A new stream after performing the map, then final join.
*/
public final <B> Stream<B> bind(final F<A, Stream<B>> f) {
return map(f).foldLeft(new F2<Stream<B>, Stream<B>, Stream<B>>() {
@Override
public Stream<B> f(Stream<B> accumulator, Stream<B> element) {
Stream<B> result = accumulator;
for (B single : element) {
result = result.cons(single);
}
return result;
}
}, Stream.<B>nil()).reverse();
}
/**
* Binds the given function across each element of this stream and the given stream with a final
* join.
*
* @param sb A given stream to bind the given function with.
* @param f The function to apply to each element of this stream and the given stream.
* @return A new stream after performing the map, then final join.
*/
public final <B, C> Stream<C> bind(final Stream<B> sb, final F<A, F<B, C>> f) {
return sb.apply(map(f));
}
/**
* Binds the given function across each element of this stream and the given stream with a final
* join.
*
* @param sb A given stream to bind the given function with.
* @param f The function to apply to each element of this stream and the given stream.
* @return A new stream after performing the map, then final join.
*/
public final <B, C> Stream<C> bind(final Stream<B> sb, final F2<A, B, C> f) {
return bind(sb, curry(f));
}
/**
* Binds the given function across each element of this stream and the given streams with a final
* join.
*
* @param sb A given stream to bind the given function with.
* @param sc A given stream to bind the given function with.
* @param f The function to apply to each element of this stream and the given streams.
* @return A new stream after performing the map, then final join.
*/
public final <B, C, D> Stream<D> bind(final Stream<B> sb, final Stream<C> sc, final F<A, F<B, F<C, D>>> f) {
return sc.apply(bind(sb, f));
}
/**
* Binds the given function across each element of this stream and the given streams with a final
* join.
*
* @param sb A given stream to bind the given function with.
* @param sc A given stream to bind the given function with.
* @param sd A given stream to bind the given function with.
* @param f The function to apply to each element of this stream and the given streams.
* @return A new stream after performing the map, then final join.
*/
public final <B, C, D, E> Stream<E> bind(final Stream<B> sb, final Stream<C> sc, final Stream<D> sd,
final F<A, F<B, F<C, F<D, E>>>> f) {
return sd.apply(bind(sb, sc, f));
}
/**
* Binds the given function across each element of this stream and the given streams with a final
* join.
*
* @param sb A given stream to bind the given function with.
* @param sc A given stream to bind the given function with.
* @param sd A given stream to bind the given function with.
* @param se A given stream to bind the given function with.
* @param f The function to apply to each element of this stream and the given streams.
* @return A new stream after performing the map, then final join.
*/
public final <B, C, D, E, F$> Stream<F$> bind(final Stream<B> sb, final Stream<C> sc, final Stream<D> sd,
final Stream<E> se, final F<A, F<B, F<C, F<D, F<E, F$>>>>> f) {
return se.apply(bind(sb, sc, sd, f));
}
/**
* Binds the given function across each element of this stream and the given streams with a final
* join.
*
* @param sb A given stream to bind the given function with.
* @param sc A given stream to bind the given function with.
* @param sd A given stream to bind the given function with.
* @param se A given stream to bind the given function with.
* @param sf A given stream to bind the given function with.
* @param f The function to apply to each element of this stream and the given streams.
* @return A new stream after performing the map, then final join.
*/
public final <B, C, D, E, F$, G> Stream<G> bind(final Stream<B> sb, final Stream<C> sc, final Stream<D> sd,
final Stream<E> se, final Stream<F$> sf,
final F<A, F<B, F<C, F<D, F<E, F<F$, G>>>>>> f) {
return sf.apply(bind(sb, sc, sd, se, f));
}
/**
* Binds the given function across each element of this stream and the given streams with a final
* join.
*
* @param sb A given stream to bind the given function with.
* @param sc A given stream to bind the given function with.
* @param sd A given stream to bind the given function with.
* @param se A given stream to bind the given function with.
* @param sf A given stream to bind the given function with.
* @param sg A given stream to bind the given function with.
* @param f The function to apply to each element of this stream and the given streams.
* @return A new stream after performing the map, then final join.
*/
public final <B, C, D, E, F$, G, H> Stream<H> bind(final Stream<B> sb, final Stream<C> sc, final Stream<D> sd,
final Stream<E> se, final Stream<F$> sf, final Stream<G> sg,
final F<A, F<B, F<C, F<D, F<E, F<F$, F<G, H>>>>>>> f) {
return sg.apply(bind(sb, sc, sd, se, sf, f));
}
/**
* Binds the given function across each element of this stream and the given streams with a final
* join.
*
* @param sb A given stream to bind the given function with.
* @param sc A given stream to bind the given function with.
* @param sd A given stream to bind the given function with.
* @param se A given stream to bind the given function with.
* @param sf A given stream to bind the given function with.
* @param sg A given stream to bind the given function with.
* @param sh A given stream to bind the given function with.
* @param f The function to apply to each element of this stream and the given streams.
* @return A new stream after performing the map, then final join.
*/
public final <B, C, D, E, F$, G, H, I> Stream<I> bind(final Stream<B> sb, final Stream<C> sc, final Stream<D> sd,
final Stream<E> se, final Stream<F$> sf, final Stream<G> sg,
final Stream<H> sh,
final F<A, F<B, F<C, F<D, F<E, F<F$, F<G, F<H, I>>>>>>>> f) {
return sh.apply(bind(sb, sc, sd, se, sf, sg, f));
}
/**
* Performs a bind across each stream element, but ignores the element value each time.
*
* @param bs The stream to apply in the final join.
* @return A new stream after the final join.
*/
public final <B> Stream<B> sequence(final Stream<B> bs) {
final F<A, Stream<B>> c = constant(bs);
return bind(c);
}
/**
* Performs function application within a stream (applicative functor pattern).
*
* @param sf The stream of functions to apply.
* @return A new stream after applying the given stream of functions through this stream.
*/
public final <B> Stream<B> apply(final Stream<F<A, B>> sf) {
return sf.bind(new F<F<A, B>, Stream<B>>() {
public Stream<B> f(final F<A, B> f) {
return map(new F<A, B>() {
public B f(final A a) {
return f.f(a);
}
});
}
});
}
/**
* Interleaves the given stream with this stream to produce a new stream.
*
* @param as The stream to interleave this stream with.
* @return A new stream with elements interleaved from this stream and the given stream.
*/
public final Stream<A> interleave(final Stream<A> as) {
return isEmpty() ? as : as.isEmpty() ? this : cons(head(), new P1<Stream<A>>() {
@Override public Stream<A> _1() {
return as.interleave(tail()._1());
}
});
}
/**
* Sort this stream according to the given ordering.
*
* @param o An ordering for the elements of this stream.
* @return A new stream with the elements of this stream sorted according to the given ordering.
*/
public final Stream<A> sort(final Ord<A> o) {
return mergesort(o, map(flip(Stream.<A>cons()).f(p(Stream.<A>nil()))));
}
// Merges a stream of individually sorted streams into a single sorted stream.
private static <A> Stream<A> mergesort(final Ord<A> o, final Stream<Stream<A>> s) {
if (s.isEmpty())
return nil();
Stream<Stream<A>> xss = s;
while (xss.tail()._1().isNotEmpty())
xss = mergePairs(o, xss);
return xss.head();
}
// Merges individually sorted streams two at a time.
private static <A> Stream<Stream<A>> mergePairs(final Ord<A> o, final Stream<Stream<A>> s) {
if (s.isEmpty() || s.tail()._1().isEmpty())
return s;
final Stream<Stream<A>> t = s.tail()._1();
return cons(merge(o, s.head(), t.head()), new P1<Stream<Stream<A>>>() {
public Stream<Stream<A>> _1() {
return mergePairs(o, t.tail()._1());
}
});
}
// Merges two individually sorted streams.
private static <A> Stream<A> merge(final Ord<A> o, final Stream<A> xs, final Stream<A> ys) {
if (xs.isEmpty())
return ys;
if (ys.isEmpty())
return xs;
final A x = xs.head();
final A y = ys.head();
if (o.isGreaterThan(x, y))
return cons(y, new P1<Stream<A>>() {
public Stream<A> _1() {
return merge(o, xs, ys.tail()._1());
}
});
return cons(x, new P1<Stream<A>>() {
public Stream<A> _1() {
return merge(o, xs.tail()._1(), ys);
}
});
}
/**
* Sort this stream according to the given ordering, using a parallel Quick Sort algorithm that uses the given
* parallelisation strategy.
*
* @param o An ordering for the elements of this stream.
* @param s A strategy for parallelising the algorithm.
* @return A new stream with the elements of this stream sorted according to the given ordering.
*/
public final Stream<A> sort(final Ord<A> o, final Strategy<Unit> s) {
return qs(o, s).claim();
}
private Promise<Stream<A>> qs(final Ord<A> o, final Strategy<Unit> s) {
if (isEmpty())
return promise(s, P.p(this));
else {
final F<Boolean, Boolean> id = identity();
final A x = head();
final P1<Stream<A>> xs = tail();
final Promise<Stream<A>> left = Promise.join(s, xs.map(flt(o, s, x, id)));
final Promise<Stream<A>> right = xs.map(flt(o, s, x, not))._1();
final Monoid<Stream<A>> m = Monoid.streamMonoid();
return right.fmap(m.sum(single(x))).apply(left.fmap(m.sum()));
}
}
private static <A> F<Stream<A>, Promise<Stream<A>>> qs_(final Ord<A> o, final Strategy<Unit> s) {
return new F<Stream<A>, Promise<Stream<A>>>() {
public Promise<Stream<A>> f(final Stream<A> xs) {
return xs.qs(o, s);
}
};
}
private static <A> F<Stream<A>, Promise<Stream<A>>> flt(final Ord<A> o,
final Strategy<Unit> s,
final A x,
final F<Boolean, Boolean> f) {
final F<F<A, Boolean>, F<Stream<A>, Stream<A>>> filter = filter();
final F<A, Boolean> lt = o.isLessThan(x);
return compose(qs_(o, s), filter.f(compose(f, lt)));
}
/**
* Projects an immutable collection of this stream.
*
* @return An immutable collection of this stream.
*/
public final Collection<A> toCollection() {
return new AbstractCollection<A>() {
public Iterator<A> iterator() {
return new Iterator<A>() {
private Stream<A> xs = Stream.this;
public boolean hasNext() {
return xs.isNotEmpty();
}
public A next() {
if (xs.isEmpty())
throw new NoSuchElementException();
else {
final A a = xs.head();
xs = xs.tail()._1();
return a;
}
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public int size() {
return length();
}
};
}
/**
* Returns a stream of integers from the given <code>from</code> value (inclusive) to the given
* <code>to</code> value (exclusive).
*
* @param from The minimum value for the stream (inclusive).
* @param to The maximum value for the stream (exclusive).
* @return A stream of integers from the given <code>from</code> value (inclusive) to the given
* <code>to</code> value (exclusive).
*/
public static Stream<Integer> range(final int from, final long to) {
return from >= to ? Stream.<Integer>nil() : cons(from, new P1<Stream<Integer>>() {
public Stream<Integer> _1() {
return range(from + 1, to);
}
});
}
/**
* Constructs a stream with the given elements.
*
* @param as The elements which which to construct a stream.
* @return a new stream with the given elements.
*/
public static <A> Stream<A> stream(final A... as) {
return as.length == 0 ? Stream.<A>nil()
: unfold(P2.tuple(new F2<A[], Integer, Option<P2<A, P2<A[], Integer>>>>() {
public Option<P2<A, P2<A[], Integer>>> f(final A[] as, final Integer i) {
return i >= as.length ? Option.<P2<A, P2<A[], Integer>>>none()
: some(P.p(as[i], P.p(as, i + 1)));
}
}), P.p(as, 0));
}
/**
* Returns a stream that is either infinite or bounded up to the maximum value of the given iterator starting at the
* given value and stepping at increments of <code>1</code>.
*
* @param e The enumerator to compute successors from.
* @param from The value to begin computing successors from.
* @return A stream that is either infinite or bounded up to the maximum value of the given iterator starting at the
* given value and stepping at increments of <code>1</code>.
*/
public static <A> Stream<A> forever(final Enumerator<A> e, final A from) {
return forever(e, from, 1L);
}
/**
* Returns a stream that is either infinite or bounded up to the maximum value of the given iterator starting at the
* given value and stepping at the given increment.
*
* @param e The enumerator to compute successors from.
* @param from The value to begin computing successors from.
* @param step The increment to step.
* @return A stream that is either infinite or bounded up to the maximum value of the given iterator starting at the
* given value and stepping at the given increment.
*/
public static <A> Stream<A> forever(final Enumerator<A> e, final A from, final long step) {
return cons(from, new P1<Stream<A>>() {
public Stream<A> _1() {
return e.plus(from, step).map(new F<A, Stream<A>>() {
public Stream<A> f(final A a) {
return forever(e, a, step);
}
}).orSome(Stream.<A>nil());
}
});
}
/**
* Returns a stream using the given enumerator from the given value to the other given value stepping at increments of
* <code>1</code>.
*
* @param e The enumerator to compute successors from.
* @param from The value to begin computing successors from.
* @param to The value to stop computing successors from.
* @return A stream using the given enumerator from the given value to the other given value stepping at increments of
* <code>1</code>.
*/
public static <A> Stream<A> range(final Enumerator<A> e, final A from, final A to) {
return range(e, from, to, 1L);
}
/**
* Returns a stream using the given enumerator from the given value to the other given value stepping at the given
* increment.
*
* @param e The enumerator to compute successors from.
* @param from The value to begin computing successors from.
* @param to The value to stop computing successors from.
* @param step The increment to step.
* @return A stream using the given enumerator from the given value to the other given value stepping at the given
* increment.
*/
public static <A> Stream<A> range(final Enumerator<A> e, final A from, final A to, final long step) {
final Ordering o = e.order().compare(from, to);
return o == EQ || step > 0L && o == GT || step < 0L && o == LT ? single(from) : cons(from, new P1<Stream<A>>() {
public Stream<A> _1() {
return Stream.join(e.plus(from, step).filter(new F<A, Boolean>() {
public Boolean f(final A a) {
return !(o == LT ? e.order().isLessThan(to, a) : e.order().isGreaterThan(to, a));
}
}).map(new F<A, Stream<A>>() {
public Stream<A> f(final A a) {
return range(e, a, to, step);
}
}).toStream());
}
});
}
/**
* Returns an infinite stream of integers from the given <code>from</code> value (inclusive).
*
* @param from The minimum value for the stream (inclusive).
* @return A stream of integers from the given <code>from</code> value (inclusive).
*/
public static Stream<Integer> range(final int from) {
return cons(from, new P1<Stream<Integer>>() {
public Stream<Integer> _1() {
return range(from + 1);
}
});
}
/**
* Returns a first-class version of the filter function.
*
* @return a function that filters a given stream using a given predicate.
*/
public static <A> F<F<A, Boolean>, F<Stream<A>, Stream<A>>> filter() {
return curry(new F2<F<A, Boolean>, Stream<A>, Stream<A>>() {
public Stream<A> f(final F<A, Boolean> f, final Stream<A> as) {
return as.filter(f);
}
});
}
/**
* Zips this stream with the given stream of functions, applying each function in turn to the
* corresponding element in this stream to produce a new stream. If this stream and the given stream
* have different lengths, then the longer stream is normalised so this function never fails.
*
* @param fs The stream of functions to apply to this stream.
* @return A new stream with a length the same as the shortest of this stream and the given stream.
*/
public final <B> Stream<B> zapp(final Stream<F<A, B>> fs) {
return fs.isEmpty() || isEmpty() ? Stream.<B>nil() :
cons(fs.head().f(head()), new P1<Stream<B>>() {
public Stream<B> _1() {
return tail()._1().zapp(fs.tail()._1());
}
});
}
/**
* Zips this stream with the given stream using the given function to produce a new stream. If
* this stream and the given stream have different lengths, then the longer stream is normalised
* so this function never fails.
*
* @param bs The stream to zip this stream with.
* @param f The function to zip this stream and the given stream with.
* @return A new stream with a length the same as the shortest of this stream and the given
* stream.
*/
public final <B, C> Stream<C> zipWith(final Stream<B> bs, final F<A, F<B, C>> f) {
return bs.zapp(zapp(repeat(f)));
}
/**
* Zips this stream with the given stream using the given function to produce a new stream. If
* this stream and the given stream have different lengths, then the longer stream is normalised
* so this function never fails.
*
* @param bs The stream to zip this stream with.
* @param f The function to zip this stream and the given stream with.
* @return A new stream with a length the same as the shortest of this stream and the given
* stream.
*/
public final <B, C> Stream<C> zipWith(final Stream<B> bs, final F2<A, B, C> f) {
return zipWith(bs, curry(f));
}
/**
* Partially-applied version of zipWith.
* Returns a function that zips a given stream with this stream using the given function.
*
* @param f The function to zip this stream and a given stream with.
* @return A function that zips a given stream with this stream using the given function.
*/
public final <B, C> F<Stream<B>, Stream<C>> zipWith(final F<A, F<B, C>> f) {
return new F<Stream<B>, Stream<C>>() {
public Stream<C> f(final Stream<B> stream) {
return zipWith(stream, f);
}
};
}
/**
* Zips this stream with the given stream to produce a stream of pairs. If this stream and the
* given stream have different lengths, then the longer stream is normalised so this function
* never fails.
*
* @param bs The stream to zip this stream with.
* @return A new stream with a length the same as the shortest of this stream and the given
* stream.
*/
public final <B> Stream<P2<A, B>> zip(final Stream<B> bs) {
final F<A, F<B, P2<A, B>>> __2 = p2();
return zipWith(bs, __2);
}
/**
* Zips this stream with the index of its element as a pair.
*
* @return A new stream with the same length as this stream.
*/
public final Stream<P2<A, Integer>> zipIndex() {
return zipWith(range(0), new F2<A, Integer, P2<A, Integer>>() {
public P2<A, Integer> f(final A a, final Integer i) {
return p(a, i);
}
});
}
/**
* Returns an either projection of this stream; the given argument in <code>Left</code> if empty,
* or the first element in <code>Right</code>.
*
* @param x The value to return in left if this stream is empty.
* @return An either projection of this stream.
*/
public final <X> Either<X, A> toEither(final P1<X> x) {
return isEmpty() ? Either.<X, A>left(x._1()) : Either.<X, A>right(head());
}
/**
* Returns an option projection of this stream; <code>None</code> if empty, or the first element
* in <code>Some</code>.
*
* @return An option projection of this stream.
*/
public final Option<A> toOption() {
return isEmpty() ? Option.<A>none() : some(head());
}
/**
* Returns a list projection of this stream.
*
* @return A list projection of this stream.
*/
public final List<A> toList() {
List<A> as = List.nil();
for (Stream<A> x = this; !x.isEmpty(); x = x.tail()._1()) {
as = as.snoc(x.head());
}
return as;
}
/**
* Returns a array projection of this stream.
*
* @return A array projection of this stream.
*/
@SuppressWarnings({"unchecked"})
public final Array<A> toArray() {
final int l = length();
final Object[] a = new Object[l];
Stream<A> x = this;
for (int i = 0; i < l; i++) {
a[i] = x.head();
x = x.tail()._1();
}
return mkArray(a);
}
/**
* Returns a array projection of this stream.
*
* @param c The class type of the array to return.