-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathalgorithm.d
3471 lines (3021 loc) · 109 KB
/
algorithm.d
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
// Written in the D programming language.
/**
This module contains functions akin to $(M map) and $(M filter), found in $(M std.algorithm).
You'll find there generalizations of these functions to act on a variadic numbers
of ranges in parallel ($(M tmap), $(M tfilter)) or to map n-ary functions on a range ($(M nmap), $(M nfilter)).
There are also many function inspired by the sequence/list/map libraries of other (functional) programming
languages (namely, Haskell, Clojure, Scala, Python) : a range comprehension,
zipping ranges, $(M reduceR), $(M fold)/$(M foldR), $(M scan)/$(M scanR), and so on.
As far as possible, all higher-order ranges presented in this module
and in $(M dranges.range) are 'tight wrappers': they are bidirectional if their input range is bidirectional,
define $(M opIndex), $(M opIndexAssign), $(M length) if it's possible, etc. That way, a good input range (for example, a random-access range)
will see its properties propagated through a chain of calls.
License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
Authors: Philippe Sigaud
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
module dranges.algorithm;
import std.algorithm,
std.array,
std.bigint,
std.conv,
std.exception,
std.functional,
std.math,
std.metastrings,
std.range,
std.stdio,
std.string,
std.traits,
std.typecons,
std.typetuple;
import dranges.functional,
dranges.predicate,
dranges.range,
dranges.templates,
dranges.tuple,
dranges.traits,
dranges.typetuple;
/**
Small one-liners to use reduce. Sum and product work on empty ranges (they return 0 and 1, respectively),
but not minOf and maxOf.
Example:
----
auto r1 = [1,2,3,4,5];
auto r2 = [-1.0,2.7818281828, 3.1415926];
assert(sum(r1) == 1+2+3+4+5);
assert(product(r1) == 1*2*3*4*5);
assert(minOf(r2) == -1.0);
assert(maxOf(r2) == 3.1415926);
----
*/
ElementType!R sum(R)(R range) if (isForwardRange!R) {
return reduce!"a+b"(to!(ElementType!R)(0), range);
}
/// ditto
ElementType!R product(R)(R range) if (isForwardRange!R) {
return reduce!"a*b"(to!(ElementType!R)(1), range);
}
/// ditto
ElementType!R maxOf(R)(R range) if (isForwardRange!R) {
enforce(!range.empty, "Do not use maxOf on empty ranges.");
return reduce!(std.algorithm.max)((ElementType!R).min, range);
}
/// ditto
ElementType!R minOf(R)(R range) if (isForwardRange!R) {
enforce(!range.empty, "Do not use minOf on empty ranges.");
return reduce!(std.algorithm.min)((ElementType!R).max,range);
}
unittest
{
auto r1 = [1,2,3,4,5];
auto r2 = [-1.0,2.7818281828, 3.1415926];
int[] r3;
assert(sum(r1) == 1+2+3+4+5);
assert(product(r1) == 1*2*3*4*5);
assert(minOf(r2) == -1.0);
assert(maxOf(r2) == 3.1415926);
assert(sum(r3) == 0.0);
assert(product(r3) == 1.0);
}
/**
Returns an associative array containing the number of times each element
is present in the range. It's a greedy algorithm: it does not work
on infinite ranges.
Example:
----
auto r = "Mississippi";
auto f = frequency(r);
assert(f['i'] == 4);
assert(f['s'] == 4);
assert(f['M'] == 1);
----
*/
size_t[ElementType!R] frequency(R)(R range) if (isInputRange!R)
{
size_t[ElementType!R] freq;
foreach(elem; range) if (elem in freq) { freq[elem]++;} else { freq[elem]=1;}
return freq;
}
unittest
{
auto r = "Mississippi";
auto f = frequency(r);
assert(f['i'] == 4);
assert(f['s'] == 4);
assert(f['M'] == 1);
}
/**
Maps a n-ary function on a range, taking n-elements segment at a time. You can use
standard functions or 'string' functions. For string functions, it will automatically determine their arity.
Examples:
----
auto r1 = [0,1,2,3,4,5,6];
auto nm1 = nmap!"a*b"(r1); // Will map "a*b" on (0,1), (1,2), (2,3), (3,4), (4,5), (5,6)
assert(equal(nm1, [0,2,6,12,20,30][]));
// Will map "a*b*c"/"a+b+c" alternatively on (0,1,2), (1,2,3), (2,3,4), (3,4,5), (4,5,6)
auto nm2 = nmap!"a%2 == 0 ? a*b*c : a+b+c"(r1);
assert(equal(nm2, [0,6,24,12,120][]));
auto nm3 = nmap!"a"(r1); // Will map "a" on (0), (1), (2), ...
assert(equal(nm3, [0,1,2,3,4,5,6][])); // Completly equivalent to map!"a"(r1)
int[] e;
auto nm4 = nmap!"a%2 == 0 ? a*b*c : a+b+c"(e); // e is empty -> cannot map a ternary function on it
assert(nm4.empty);
----
*/
NMapType!(fun, R) nmap(alias fun, R)(R range) if (isForwardRange!R)
{
auto s = segment!(arity!fun)(range);
alias Prepare!(fun, TypeNuple!(ElementType!R, arity!fun)) pfun;
return map!pfun(s);
}
template NMapType(alias fun, R)
{
alias Map!(Prepare!(fun, TypeNuple!(ElementType!R, arity!fun)), Knit!(TypeNuple!(R, arity!fun))) NMapType;
}
unittest
{
auto r1 = [0,1,2,3,4,5,6];
auto nm1 = nmap!"a*b"(r1); // Will map "a*b" on (0,1), (1,2), (2,3), (3,4), (4,5), (5,6)
assert(equal(nm1, [0,2,6,12,20,30][]));
auto nm2 = nmap!"a%2 == 0 ? a*b*c : a+b+c"(r1); // Will map "a*b*c"/"a+b+c" alternatively on (0,1,2), (1,2,3), (2,3,4), (3,4,5), (4,5,6)
assert(equal(nm2, [0,6,24,12,120][]));
auto nm3 = nmap!"a"(r1); // Will map "a" on (0), (1), (2), ...
assert(equal(nm3, [0,1,2,3,4,5,6][])); // Completly equivalent to map!"a"(r1)
int[] e;
auto nm4 = nmap!"a%2 == 0 ? a*b*c : a+b+c"(e); // e is empty -> cannot map a ternary function on it
assert(nm4.empty);
}
/**
Maps a n-args function on either n ranges in parallel or on an n-tuple producing range.
Examples:
----
// With functions mapped on n ranges in parallel:
auto r1 = [1,2,3,4,5,6];
string s = "abcdefghijk";
auto tm1 = tmap!"replicate(a,b)"(r1,s); // [a], [b,b], [c,c,c], [d,d,d,d], ...
assert(equal(flatten(tm1), "abbcccddddeeeeeffffff")); // Note the use of flatten
auto tm2 = tmap!"a%2 == 0 ? b : '_'"(r1,s); // alternate between a char from s and '_'
assert(equal(tm2, "_b_d_f"));
auto tm3 = tmap!"a%2==0 ? b : c"(r1,s,flatten(tm1)); // ternary function mapped on three ranges in parallel
assert(equal(tm3, "abbdcf"));
string e = "";
assert(tmap!"a"(r1, s, e).empty); // e is empty -> tmap also
----
Examples:
----
// With functions mapped on a tuple-producing range:
auto tf = tfilter!"a%2"(r1, s); // keeps the odd elements from r1, produces 2-tuples (1,'a'),(3,'c'),(5,'e')
string foo(int a, char b) { return to!string(array(replicate(a,b)));}
auto tm4 = tmap!foo(tf); // maps a standard binary function on a 2-tuple range
assert(equal(tm4, ["a","ccc","eeeee"][]));
auto r2 = [1,2,3][];
// combinations(r2,r2) is equivalent to [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)][]
auto combs = tmap!"a*b"(combinations(r2,r2));
assert(equal(combs, [1,2,3,2,4,6,3,6,9][]));
----
*/
TMapType!(fun, R) tmap(alias fun, R...)(R ranges) if (allSatisfy!(isForwardRange,R) && (R.length > 1) || (R.length == 1 && !is(ElementType!R.Types)))
{
alias Prepare!(fun, staticMap!(Unqual, ElementTypes!R)) pfun;
return map!pfun(knit(ranges));
}
/// ditto
TMapType!(fun, R) tmap(alias fun, R)(R r) if (isTupleRange!R)
{
alias ElementType!R ET;
alias Prepare!(fun, staticMap!(Unqual, ElementType!R.Types)) pfun;
return map!pfun(r);
}
template TMapType(alias fun, R...) if (allSatisfy!(isForwardRange,R) && (R.length > 1) || (R.length == 1 && !is(ElementType!R.Types)))
{
alias Map!(Prepare!(fun, staticMap!(Unqual, ElementTypes!R)), Knit!R) TMapType;
}
template TMapType(alias fun, R) if (isTupleRange!R)
{
alias Map!(Prepare!(fun, /+staticMap!(Unqual,+/ ElementType!R.Types), R) TMapType;
}
unittest
{
auto r1 = [1,2,3,4,5,6];
auto s = cast(char[])"abcdefghijk";
auto tm1 = tmap!"replicate(a,b)"(s,r1); // [a], [b,b], [c,c,c], [d,d,d,d], ...
alias typeof(tm1) TM1;
assert(equal(concat(tm1), cast(char[])"abbcccddddeeeeeffffff")); // Note the use of flatten
auto tm2 = tmap!"a%2 == 0 ? b : '_'"(r1,s);
assert(equal(tm2, "_b_d_f"));
auto tm3 = tmap!"a%2==0 ? b : c"(r1,s,concat(tm1));
assert(equal(tm3, "abbdcf"));
string e = "";
assert(tmap!"a"(r1, s, e).empty); // e is empty -> tmap also
auto tf = tfilter!"a%2"(r1, s); // keeps the odd elements from r1, produces 2-tuples (1,'a'),(3,'c'),(5,'e')
string foo(int a, dchar b) { return to!(string)(array(replicate(b,a)));}
auto tm4 = tmap!foo(tf); // maps a standard binary function on a 2-tuple range
assert(equal(tm4, ["a","ccc","eeeee"][]));
auto r2 = [1,2,3][];
// combinations(r2,r2) is equivalent to [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)][]
auto combs = tmap!"a*b"(combinations(r2,r2));
assert(equal(combs, [1,2,3,2,4,6,3,6,9][]));
}
/**
nfilter takes a n-args predicate and a range and outputs the n-uplets that verify the predicate.
As with other n-args functions on ranges (dropWhile, takeWhile, nmap, ...) it accepts
'string' functions and adapts its behavior accordingly.
It also takes an optional step argument, defaulting to 1 (see the examples).
To use it easily with other ranges, nfilter produces tuples, not arrays.
That also means that if you use a unary predicate it will produce the same
values than std.algorithm.filter but wrapped in a tuple. (tuple(1), ...)
TODO:
Fuse the array-returning version and the tuple-returning version and control the behavior with a policy. Do that also
with the sibling functions: dropWhile, takeWhile, nmap.
Example:
----
auto r1 = [0,1,2,3,3,5,4,3,2,1,0];
int foo(int a, int b, int c) { return a<=b && b<=c;} // increase on three elements
auto nf1 = nfilter!(foo)(r1);
assert(equal(nf1, [tuple(0,1,2), tuple(1,2,3), tuple(2,3,3), tuple(3,3,5)][]));
auto nf2 = nfilter!"a<=b && b<=c"(r1); // The same with a string function.
// Automatically deduces that the predicate is a 3-args function.
assert(equal(nf2, [tuple(0,1,2), tuple(1,2,3), tuple(2,3,3), tuple(3,3,5)][]));
auto nf3 = nfilter!("a == b-1 || a == b+1", 2)(r1); // step of 2, will test (0,1) (2,3), (3,5), (4,3), (2,1)
assert(equal(nf3, [tuple(0,1), tuple(2,3), tuple(4,3), tuple(2,1)][]));
auto nf4 = nfilter!"a>100"(r1); // this predicate is always false
assert(nf4.empty); // the filtered range is empty.
----
*/
NFilterType!(fun, step, R) nfilter(alias fun, size_t step =1, R)(R range)
if (isForwardRange!R)
{
alias Prepare!(fun, TypeNuple!(ElementType!R, arity!fun)) pfun;
return filter!pfun(stride(segment!(arity!fun)(range), step));
}
template NFilterType(alias fun, size_t step, R) {
alias Filter!(Prepare!(fun, TypeNuple!(ElementType!R, arity!fun)), Stride!(Knit!(TypeNuple!(R, arity!fun)))) NFilterType;
}
unittest
{
auto r1 = [0,1,2,3,3,5,4,3,2,1,0];
int foo(int a, int b, int c) { return a<=b && b<=c;} // increase on three elements
auto nf1 = nfilter!(foo)(r1);
assert(equal(nf1, [tuple(0,1,2), tuple(1,2,3), tuple(2,3,3), tuple(3,3,5)][]));
auto nf2 = nfilter!"a<=b && b<=c"(r1);
assert(equal(nf2, [tuple(0,1,2), tuple(1,2,3), tuple(2,3,3), tuple(3,3,5)][]));
auto nf3 = nfilter!("a == b-1 || a == b+1", 2)(r1); // step of 2, will test (0,1) (2,3), (3,5), (4,3), (2,1)
assert(equal(nf3, [tuple(0,1), tuple(2,3), tuple(4,3), tuple(2,1)][]));
auto nf4 = nfilter!"a>100"(r1);
assert(nf4.empty);
int[] e;
assert(nfilter!"a"(e).empty);
}
/**
tfilter stands for tuple-filter: it either filters a variadic list of ranges in lockstep,
with a n-args predicate spanning all ranges or filters a tuple-returning range with a function.
In all cases, it returns the n-tuples that satisfy the predicate.
It can take standard functions or 'string' functions.
The first arg will be filled with the front from the first field or range element, the second arg with the second field or range and so on.
That's a,b,c,d... for a string function.
Examples:
----
// Filtering n ranges in parallel
auto r1 = [ 0, 1, 2, 3, 4, 5];
auto r2 = [ 3.0, 4.0, 5.0, 6.0];
string[] r3 = ["a", "b", "cc"];
// standard function
bool pred(int a, double b, string c) { return (a<b) && (c.length>1);}
auto tf1 = tfilter!(pred)(r1,r2,r3);
assert(equal(tf1, [tuple(2, 5.0, "cc")][])); // tf1 is just (2, 5.0, "cc)
// string function
auto tf2 = tfilter!"a<b && c.length>1"(r1,r2,r3); // knows arity must be 3. Will instantiate the (int,double,string) version
assert(equal(tf2, [tuple(2, 5.0, "cc")][])); // tf2 is equal to tf1
auto tf3 = tfilter!"a*a>b"(r1, r2);
assert(equal(tf3, [tuple(3, 6.0)][])); // Only one tuple satisfies a*a>b before reaching the end of r2
// templated predicate
bool pred2(T,U)(T t, U u) { return t*t>u;}
auto tf4 = tfilter!(pred2!(int, double))(r1, r2); // it doesn't automatically instantiate the correct function from a template.
assert(equal(tf4, [tuple(3,6.0)][])); // because tfilter has no way to know which types the template is waiting for.
----
Example:
----
// Filtering a tuple-returning range with a function:
// combinations(r1,r3) is equivalent to [(0,"a"),(0,"b"),(0,"cc"),(1,"a), ..., (5,"a),(5,"b),(5,"cc")][]
auto tf5 = tfilter!"a%2 && b.length>1"(combinations(r1,r3));
assert(equal(tf5, [tuple(1,"cc"),tuple(3,"cc"),tuple(5,"cc")][]));
----
*/
TFilterType!(fun, R) tfilter(alias fun, R...)(R ranges)
if (allSatisfy!(isForwardRange, R) && ((R.length > 1) || (R.length == 1 && !is(ElementType!R.Types))))
{
alias Prepare!(fun, staticMap!(Unqual, ElementTypes!R)) pfun;
return filter!pfun(knit(ranges));
}
/// ditto
TFilterType!(fun, R) tfilter(alias fun, R)(R range)
if (isForwardRange!R && is(ElementType!R.Types))
{
alias ElementType!R ET;
alias Prepare!(fun, staticMap!(Unqual, ET.Types)) pfun;
return filter!pfun(range);
}
template TFilterType(alias fun, R...)
if (allSatisfy!(isForwardRange, R) && ((R.length > 1) || (R.length == 1 && !is(ElementType!R.Types))))
{
alias Filter!(Prepare!(fun, staticMap!(Unqual, ElementTypes!R)), Knit!R) TFilterType;
}
template TFilterType(alias fun, R)
if (isForwardRange!R && is(ElementType!R.Types))
{
alias Filter!(Prepare!(fun, staticMap!(Unqual, ElementType!R.Types)), R) TFilterType;
}
unittest
{
auto r1 = [ 0, 1, 2, 3, 4, 5];
auto r2 = [ 3.0, 4.0, 5.0, 6.0];
string[] r3 = ["a", "b", "cc"];
// standard function test
bool pred(int a, double b, string c) { return (a<b) && (c.length>1);}
auto tf1 = tfilter!pred(r1,r2,r3);
assert(equal(tf1, [tuple(2, 5.0, "cc")][])); // tf1 is just (2, 5.0, "cc)
// string function test
auto tf2 = tfilter!"a<b && c.length>1"(r1,r2,r3); // knows arity must be 3.
assert(equal(tf2, [tuple(2, 5.0, "cc")][])); // tf2 is equal to tf1
auto tf3 = tfilter!"a*a>b"(r1, r2);
assert(equal(tf3, [tuple(3, 6.0)][])); // Only one tuple satisfies a*a>b before reaching the end of r2
// templated predicate
bool pred2(T,U)(T t, U u) { return t*t>u;}
auto tf4 = tfilter!(pred2!(int, double))(r1, r2);
assert(equal(tf4, [tuple(3,6.0)][]));
string[] e;
assert(tfilter!pred(r1, r2, e).empty); // one range empty => TFilter is empty also
// combinations(r1,r3) is equivalent to [(0,"a"),(0,"b"),(0,"cc"),(1,"a), ..., (5,"a),(5,"b),(5,"cc")][]
auto tf5 = tfilter!"a%2 && b.length>1"(combinations(r1,r3));
assert(equal(tf5, [tuple(1,"cc"),tuple(3,"cc"),tuple(5,"cc")][]));
}
/+
/**
Another implementation of reduceR. It uses recursion so it's quite limited in its depth.
*/
ElementType!R reducer(alias fun,R)(R range) if (isInputRange!R && !isInfinite!R)
{
auto f = range.front;
range.popFront;
alias naryFun!fun nfun;
return range.empty ? f : nfun(f, reducer!fun(range));
}
+/
/**
The complementary function to reduce: it reduces a (bidirectional) range from the right
reduce!fun(seed, range) applies successively the binary function fun
to the left elements of range (beginning with seed)
and produces fun(fun(... fun(fun(seed, range.front), range[1])...)).
By comparison, reduceR!fun(seed, range) applies successively fun to the right elements of range (also beginning
with seed or range.back, if seed is not given) and produces: fun(fun(... fun(range[$-2], fun(range.back, seed)) ...)).
If fun is not a commutative operation (that is, if fun(a,b) != fun(b,a) in general), then reduceR will
produce different results from reduce. See for example the lines with reduce!"a/b" and reduceR!"a/b".
Like reduce, it accepts many functions at the same time. In that case, the result is a tuple of the different values.
Note:
It's completly based on std.algorithm.reduce's code.
Example:
----
auto a = [ 3, 4 ];
auto r = reduce!("a + b")(0, a);
assert(r == 7);
auto rR = reduceR!("a + b")(0, a); // a+b is commutative -> same result than reduce
assert(rR == 7);
r = reduce!"a+b"(a);
assert(r == 7);
rR = reduceR!"a+b"(a); // Without seed value
assert(rR == 7);
auto a2 = [1.0,2.0,3.0,4.0];
auto r2 = reduce!"a / b"(a2);
assert(r2 == (((1.0)/2.0)/3.0)/4.0 );
auto rR2 = reduceR!"a / b"(a2);
assert(rR2 == 1.0/(2.0/(3.0/(4.0))) ); // a/b is not a commutative operation
a = [ 1, 2, 3, 4, 5 ];
// Stringize with commas
// the function has been 'symmetrized' compared to reduce's unittest
string rep = reduce!("to!string(a) ~ `, ` ~ to!(string)(b)")("", a);
assert(rep[2 .. $] == "1, 2, 3, 4, 5");
string repR = reduceR!("to!string(a) ~ `, ` ~ to!string(b)")("", a);
assert(repR[0 .. $-2] == "1, 2, 3, 4, 5");
// Continued fraction
double continuedFraction(double a, double b) { return a + 1.0/b;}
auto piFrac = [3, 7, 15, 1, 292]; // pi continued fraction,
// 3.141592 is approx. 3 + 1/(7 + 1/(15 + 1/(1 + 1/(292 + 1/...))))
auto pi2 = reduceR!continuedFraction(piFrac); // calculates the continued fraction: needs reduceR as reduce wouldn't make it
assert(approxEqual(pi2, PI)); // check
----
*/
template reduceR(fun...)
{
alias ReduceR!(fun).reduceR reduceR;
}
template ReduceR(fun...)
{
private:
static if (fun.length > 1)
{
template TypeTupleN(E, int n)
{
static if (n == 1) alias E TypeTupleN;
else alias TypeTuple!(E, TypeTupleN!(E, n - 1)) TypeTupleN;
}
enum L = fun.length;
template ReturnType(E)
{
alias Tuple!(TypeTupleN!(E, L)) ReturnType;
}
}
else
{
template ReturnType(E)
{
alias E ReturnType;
}
}
public:
Unqual!E reduceR(E, R)(E seed, R r)
{
Unqual!E result = seed;
foreach_reverse(e; r)
{
static if (fun.length == 1)
{
result = binaryFun!(fun[0])(e, result);
}
else
{
foreach (i, Unused; typeof(E.field))
{
result.field[i] = binaryFun!(fun[i])(e, result.field[i]);
}
}
}
return result;
}
ReturnType!(ElementType!(Range))
reduceR(Range)(Range r) if (isBidirectionalRange!Range)
{
enforce(!r.empty);
static if (fun.length == 1)
{
auto e = r.back;
}
else
{
typeof(return) e;
foreach (i, Unused; typeof(typeof(return).field))
{
e.field[i] = r.back;
}
}
r.popBack;
return reduceR(e, r);
}
}
unittest // taken from std.algorithm.reduce unittest
{
auto a = [ 3, 4 ];
auto r = reduce!("a + b")(0, a);
assert(r == 7);
auto rR = reduceR!("a + b")(0, a);
assert(rR == 7);
r = reduce!("a + b")(a);
assert(r == 7);
rR = reduceR!("a + b")(a);
assert(rR == 7);
auto a2 = [1.0,2.0,3.0,4.0];
auto r2 = reduce!("a / b")(a2);
assert(r2 == ((1.0/2.0)/3.0)/4.0);
auto rR2 = reduceR!("a / b")(a2);
assert(rR2 == 1.0/(2.0/(3.0/4.0))); // a/b is not a commutative operation: it will give different results for reduce and reduceR
r = reduce!(min)(a);
assert(r == 3);
rR = reduceR!(min)(a);
assert(rR == 3);
/*
auto b = [ 100 ];
auto r1 = reduce!("a + b")(chain(a, b));
assert(r1 == 107);
auto rR1 = reduceR!("a + b")(chain(a, b));
assert(rR1 == 107);
*/
// two funs
auto r3 = reduce!("a + b", "a - b")(tuple(0, 0), a);
assert(r3.field[0] == 7 && r3.field[1] == -7);
auto rR3 = reduceR!("a + b", "a - b")(tuple(0, 0), a);
assert(rR3.field[0] == 7 && rR3.field[1] == -1);
auto r4 = reduce!("a + b", "a - b")(a);
assert(r4.field[0] == 7 && r4.field[1] == -1);
auto rR4 = reduceR!("a + b", "a - b")(a);
assert(rR4.field[0] == 7 && rR4.field[1] == -1);
a = [ 1, 2, 3, 4, 5 ];
// Stringize with commas
string rep = reduce!("to!string(a) ~ `, ` ~ to!(string)(b)")("", a); // the function has been 'symmetrized' compare to reduce's unittest
assert(rep[2 .. $] == "1, 2, 3, 4, 5");
string repR = reduceR!("to!string(a) ~ `, ` ~ to!string(b)")("", a);
assert(repR[0 .. $-2] == "1, 2, 3, 4, 5");
// Continued fraction
double continuedFraction(double a, double b) { return to!double(a) + 1.0/b;}
double[] piFrac = [3, 7, 15, 1, 292]; // pi contined fraction (ie 3.141592 '=' 3 + 1/(7 + 1/(15 + 1/(1 + 1/(292))))
auto pi2 = reduceR!continuedFraction(piFrac);
assert(approxEqual(pi2, PI));
}
/**
Given a function fun and a seed value, iterate repeatedly applies fun
and produces the infinite range seed, fun(seed), fun(fun(seed)), fun(fun(fun(seed))), ...
opIndex is defined, but may take some time (if you ask for a high index).
Example:
----
// Generating the natural numbers
auto natural = iterate!"a+1"(0); // 0,1,2,3,4,5, (as ints)
assert(equal(take(5, natural), [0,1,2,3,4][]));
// Generating powers of two
auto powersOf(size_t n)() { return iterate!(to!string(n) ~ "*a")(1L); // 1, n, n*n, n*n*n, n*n*n*n (as longs)
assert(equal(take(5, powersOf!2), [1,2,4,8,16][]));
assert(powersOf!2[10] == 1024); // opIndex is defined
// Converging on a value
// (x+n/x)/2 applied repeatedly converges towards sqrt(n)
auto sqrtOf(size_t n)() {
return iterate!Format("(a + %s/a)/2", n)(1.0);
}
auto sqrt2 = sqrtOf!2; // Converges towards sqrt(2), 1.414
popFrontN(sqrt2, 4); // letting it converge
assert(approxEqual(sqrt2.front, sqrt(2.0), 0.0000001)); // 5 iterations, already quite good
// Conway's 'Look and Say' sequence
// http://en.wikipedia.org/wiki/Look_and_say_sequence
int[] LookAndSay(int[] r) {
int[] e;
return reduce!"a ~ b.field[1] ~ b.field[0]"(e, std.algorithm.group(r));
}
auto conwaySequence = iterate!LookAndSay([1][]);
assert(equal(take(6, conwaySequence), [[1][], /+ One 1 +/
[1,1][], /+ Two 1s +/
[2,1][], /+ One 2, one 1+/
[1,2,1,1][], /+ One 1, one 2, two 1s+/
[1,1,1,2,2,1][],/+ Three 1s, two 2s, one 1+/
[3,1,2,2,1,1][]
][]));
----
*/
struct Iterate(alias fun, S) {
S _seed;
this(S seed) { _seed = seed;}
enum bool empty = false; // Infinite range
S front() { return _seed;}
@property Iterate save() { return this;}
void popFront() { _seed = unaryFun!fun(_seed);}
S opIndex(size_t n) {
S result = _seed;
foreach(i;0..n) result = unaryFun!fun(result);
return result;
}
}
/// ditto
Iterate!(fun, S) iterate(alias fun, S)(S seed)
{
return Iterate!(fun, S)(seed);
}
//version(unittest)
//{
int[] LookAndSay(int[] r) {
int[] e;
return reduce!"a ~ b.field[1] ~ b.field[0]"(e, std.algorithm.group(r));
}
//}
unittest
{
// Generating the natural numbers
auto natural = iterate!"a+1"(1); // 1,2,3,4,5, (as ints)
assert(equal(take(natural, 5), [1,2,3,4,5][]));
assert(isInfinite!(typeof(natural)));
// Generating powers of two
auto powersOf(size_t n)() { return iterate!(to!string(n) ~ "*a")(1L);} // 1, n, n*n, n*n*n, n*n*n*n (as longs)
assert(equal(take(powersOf!2, 5), [1,2,4,8,16][]));
assert(powersOf!2[10] == 1024); // opIndex is defined
// Converging on a value
// (x+n/x)/2 applied repeatedly converges towards sqrt(n)
auto sqrtOf(size_t n)() {
return iterate!(Format!("(a+%s/a)/2", n))(1.0);
}
auto sqrt2 = sqrtOf!2; // Converges towards sqrt(2), 1.414
popFrontN(sqrt2, 4); // letting is converge
assert(approxEqual(sqrt2.front, sqrt(2.0), 0.0000001)); // 5 iterations, already quite good
// Conway's 'Look and Say' sequence
// http://en.wikipedia.org/wiki/Look_and_say_sequence
auto conwaySequence = iterate!LookAndSay([1]); // version(unittest)
assert(equal(take(conwaySequence, 6), [[1][], /+ One 1 +/
[1,1][], /+ Two 1s +/
[2,1][], /+ One 2, one 1+/
[1,2,1,1][], /+ One 1, one 2, two 1s+/
[1,1,1,2,2,1][],/+ Three 1s, two 2s, one 1+/
[3,1,2,2,1,1][]
][]));
}
/**
A range that produces the successive result of reduce!fun(seed, range).
[seed, fun(seed, range.front), fun(fun(seed, range.front), range[1]), ...]
It's useful to get moving calculations, like moving sums, products, minima, etc.
Taken from Haskell.
Note:
only the one-function version is implemented. scan!(max, min, foo)(r) is not possible right now,
though not difficult to code...
Example:
----
// moving sum
auto r1 = [1,2,3,4];
auto s = scan!"a+b"(0,r1);
assert(equal(s, [0,1,3,6,10][])); // 0, 0+1, 0+1+2, 0+1+2+3, 0+1+2+3+4
s = scan!"a+b"(r1);
assert(equal(s, [1,3,6,10][])); // 1, 1+2, 1+2+3, 1+2+3+4
// factorials
auto fac = scan!"a*b"(1L, numbers(1)); // numbers(1) is 1,2,3,4,5,6,...
assert(equal(take(fac,6), [1,1,2,6,24,120][])); // 1, 1*1, 1*1*2, 1*1*2*3, 1*1*2*3*4, 1*1*2*3*4*5
//Moving minima
auto r2 = [1,2, -1, -4, 0, 3, 4];
auto r = scan!min(0,r2);
assert(equal(r, [0,0,0,-1,-4,-4,-4,-4][]));
r = scan!min(r2);
assert(equal(r, [1,1,-1,-4,-4,-4,-4][]));
----
*/
struct Scan(alias fun, S, R) if (isForwardRange!R)// && CompatibilityFuncArgs!(fun, S, R))
{
S _result;
R _range;
bool done;
this(S seed, R range)
{
_range = range;
_result = seed;
if (range.empty) done = true;
}
bool empty() {return _range.empty && done;}
S front() { return _result;}
@property Scan save() { return this;}
void popFront()
{
if (!_range.empty)
{
_result = binaryFun!(fun)(_result, _range.front);
_range.popFront;
}
else
{
done = true;
}
}
}
/// ditto
Scan!(fun, S, R) scan(alias fun, S, R)(S seed, R range) if (isForwardRange!R)// && CompatibilityFuncArgs!(fun, S, R))
{
return Scan!(fun, S, R)(seed, range);
}
/// ditto
Scan!(fun, ElementType!R, R) scan(alias fun, R)(R range) if (isForwardRange!R)// && CompatibilityFuncArgs!(fun, R))
{
ElementType!R seed;
if (!range.empty)
{
seed = range.front;
range.popFront;
} // if range is empty, seed == (ElementType!R).init, but Scan will be empty anyway
return Scan!(fun, ElementType!R, R)(seed, range);
}
unittest
{
// moving sum
auto r1 = [1,2,3,4];
auto s = scan!"a+b"(0,r1);
assert(equal(s, [0,1,3,6,10][]));
s = scan!"a+b"(r1);
assert(equal(s, [1,3,6,10][]));
// factorial
auto f = scan!"a*b"(1L, drop(numbers(),1));
assert(equal(take(f,6), [1,1,2,6,24,120][]));
// moving minima
auto r2 = [1,2, -1, -4, 0, 3, 4];
auto r = scan!min(0,r2);
assert(equal(r, [0,0,0,-1,-4,-4,-4,-4][]));
r = scan!min(r2);
assert(equal(r, [1,1,-1,-4,-4,-4,-4][]));
int[] e;
assert(scan!"a+b"(e).empty);
}
/**
A variation on scan: this range returns the same values than scan, but paired
with the rest of the range.
Example:
----
auto arr = [1,2,3,4];
// running sum
assert(equal(scan!"a+b"(0,arr), [0,1,3,6,10]));
// sum with rest of range
assert(equal(scan2!"a+b"(0,arr), [tuple(0, [1,2,3,4][]),
tuple(1, [2,3,4][]),
tuple(3, [3,4][]),
tuple(6, [4][]),
tuple(10,(int[]).init)]));
----
*/
struct Scan2(alias fun, S, R) if (isForwardRange!R)// && CompatibilityFuncArgs!(fun, S, R))
{
S _result;
R _range;
bool done;
this(S seed, R range)
{
_range = range;
_result = seed;
}
bool empty() {return _range.empty && done;}
Tuple!(S,R) front() { return tuple(_result, _range);}
@property Scan2 save() { return this;}
void popFront()
{
if (!_range.empty)
{
_result = binaryFun!(fun)(_result, _range.front);
_range.popFront;
}
else
{
done = true;
}
}
}
/// ditto
Scan2!(fun, S, R) scan2(alias fun, S, R)(S seed, R range) if (isForwardRange!R)// && CompatibilityFuncArgs!(fun, S, R))
{
return Scan2!(fun, S, R)(seed, range);
}
/// ditto
Scan2!(fun, ElementType!R, R) scan2(alias fun, R)(R range) if (isForwardRange!R)// && CompatibilityFuncArgs!(fun, R))
{
ElementType!R seed;
if (!range.empty)
{
seed = range.front;
range.popFront;
}
return Scan2!(fun, ElementType!R, R)(seed, range);
}
/**
The cousin of scan. A range that produces the successive result of reduceR!fun(seed, range):
[seed, fun(range.back, seed), fun(range[1], fun(range.back, seed)), ...]
Taken from Haskell.
See_Also: scan, reduce, reduceR
Example:
----
auto r1 = [1,2,3,4];
auto s = scanR!"a+b"(0,r1); // moving sum
assert(equal(s, [0,4,7,9,10][])); // 0, 4+0, 3+4+0, 2+3+4+0, 1+2+3+4+0
s = scanR!"a+b"(r1);
assert(equal(s, [4,7,9,10][]));
auto r2 = [1,2, -1, -4, 0, 3, 4];
auto r = scanR!min(0,r2); // moving minimum
assert(equal(r, [0,0,0,0,-4,-4,-4,-4][]));
r = scanR!min(r2);
assert(equal(r, [4,3,0,-4,-4,-4,-4][]));
int[] e;
assert(scanR!"a+b"(e).empty);
----
*/
struct ScanR(alias fun, S, R) if (isBidirectionalRange!R)// && CompatibilityFuncArgs!(fun, S, R))
{
S _result;
R _range;
bool done;
this(S seed, R range)
{
_range = range;
_result = seed;
if (range.empty) done = true;
}
bool empty() {return _range.empty && done;}
S front() { return _result;}
@property ScanR save() { return this;}
void popFront()
{
if (!_range.empty)
{
_result = binaryFun!(fun)(_range.back,_result);
_range.popBack;
}
else
{
done = true;
}
}
}
/// ditto
ScanR!(fun, S, R) scanR(alias fun, S, R)(S seed, R range) if (isBidirectionalRange!R)// && CompatibilityFuncArgs!(fun, S, R))
{
return ScanR!(fun, S, R)(seed, range);
}
/// ditto
ScanR!(fun, ElementType!R, R) scanR(alias fun, R)(R range) if (isBidirectionalRange!R)// && CompatibilityFuncArgs!(fun, R))
{
ElementType!R seed;
if (!range.empty)
{
seed = range.back;
range.popBack;
} // if range is empty, seed == (ElementType!R).init, but ScanR will be empty anyway
return ScanR!(fun, ElementType!R, R)(seed, range);
}
unittest
{
auto r1 = [1,2,3,4];
auto s = scanR!"a+b"(0,r1); // moving sum
assert(equal(s, [0,4,7,9,10][])); // 4, 3+4, 2+3+4, 1+2+3+4
s = scanR!"a+b"(r1);
assert(equal(s, [4,7,9,10][]));
auto r2 = [1,2, -1, -4, 0, 3, 4];
auto r = scanR!min(0,r2); // moving minimum
assert(equal(r, [0,0,0,0,-4,-4,-4,-4][]));
r = scanR!min(r2);
assert(equal(r, [4,3,0,-4,-4,-4,-4][]));
int[] e;
assert(scanR!"a+b"(e).empty);
}
/**
To Be Documented.
The n-ranges-in-parallel version of scan.
*/
struct TScan(alias fun, S, R...) if (allSatisfy!(isForwardRange,R))
{
S _result;
Knit!R _ranges;
bool done;
this(S seed, R ranges)
{
_ranges = knit(ranges);