-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfunctional.d
1793 lines (1513 loc) · 52.9 KB
/
functional.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 all the function-related templates.
Its main use used to be to generate functions from strings, with the $(M naryFun) template,
an extension of $(M std.functional.unaryFun) and $(M binaryFun). Now, it presents a nice collection
of adaptors and transformers: functions or templates acting on functions to transform them.
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.functional;
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 core.vararg;
import dranges.algorithm,
dranges.patternmatch,
dranges.predicate,
dranges.range,
dranges.templates,
dranges.traits,
dranges.tuple,
dranges.typetuple;
/**
Gives the _arity of a function: unary, binary, etc. A 0-args function has an _arity of 0.
----
int foo0() { return 0;}
int foo1(int a) { return a;}
int foo2(int a, int b) { return a+b;}
assert(arity!foo0 == 0);
assert(arity!foo1 == 1);
assert(arity!foo2 == 2);
----
It does not work on non-instantiated template functions (because they
are not functions) and gives an _arity of 1 for variadic functions, because
their variadic list is considered as one arg.
----
T foo(T)(T t) { ...};
auto a = arity!foo; // error !
auto b = arity!(foo!int); // OK.
//
int foov(int a...) { return 0;}
assert(arity!foov == 1);
----
See_Also: $(M dranges.templates.TemplateFunArity).
*/
template arity(alias fun) if (isFunction!fun) {
enum size_t arity = ParameterTypeTuple!(fun).length;
}
template arity(string fun)
{
alias aritySImpl!(" " ~ fun ~ " ",0).result arity;
}
unittest {
int foo0() { return 0;}
int foo1(int a) { return a;}
int foo2(int a, int b) { return a+b;}
T foo3(T, U)(T t, T tt, U u) { return t;} // templated
assert(arity!foo0 == 0);
assert(arity!foo1 == 1);
assert(arity!foo2 == 2);
assert(!__traits(compiles, arity!foo3)); // does not work on non-instantiated functions
assert(arity!(foo3!(int,double)) == 3); // foo3!(int, double) is a 3-args function
int foov(int a...) { return 0;}
assert(arity!foov == 1);
}
/// Given a bunch of functions names, gives the typetuple of their return types. Used by $(M juxtapose).
template ReturnTypes(Funs...)
{
alias MapOnAlias!(ReturnType, Funs) ReturnTypes;
}
/// Given a bunch of functions names, gives the (flattened) typetuple of their return values. Used by $(M juxtapose).
template ParameterTypeTuples(alias fun, Rest...)
{
alias MapOnAlias!(ParameterTypeTuple, fun, Rest) ParameterTypeTuples;
}
template SumOfArity(size_t zero, alias fun)
{
enum size_t SumOfArity = zero + arity!fun;
}
template SumOfArities(F...)
{
alias StaticScan!(SumOfArity, 0, F) SumOfArities;
}
template SumOfReturn(size_t zero, alias fun)
{
static if (is(ReturnType!fun == void))
enum size_t SumOfReturn = zero;
else
enum size_t SumOfReturn = zero + 1;
}
template SumOfReturns(Funs...)
{
alias StaticScan!(SumOfReturn, 0, Funs) SumOfReturns;
}
/**
Takes n functions and create a new one, taking as arguments the concatenation of all input functions
arguments and returning a tuple of their results. It will deal correctly with nullary (0-arg) functions
by inserting their return value at the right place and with void-returning functions.
Do not use variadic functions, though.
This template is very useful when dealing with tuple-returning ranges.
Example:
----
int foo(int i) { return i*i;} // int -> int
int bar() { return 0;} // () -> int
void baz(string s) {} // string -> ()
double[] quux(double d, double[] f) // (double,double[]) -> double[]
{ return f ~ d;}
alias juxtapose!(foo,bar,baz,quux) jux; // jux takes (int,string, double, double[]), returns Tuple!(int,int,double[]);
auto ir = [0,1,2,3,4,5];
auto sr = ["abc", "def","ghijk"];
auto dr = [3.14,2.78,1.00,-1.414];
auto fr = [[0.1,0.2], [0.0,-1.0,-2.0]];
auto m = tmap!jux(ir,sr,dr,fr);
----
Note: another, more mathematical way, to look at it is that $(M _juxtapose) creates a function whose type is the product the input functions' types.
In D, product of types are tuples.
*/
template juxtapose(Funs...)
{
Tuple!(StaticFilter!(isNotVoid, ReturnTypes!Funs)) juxtapose(ParameterTypeTuples!Funs params) {
typeof(return) result;
alias SumOfArities!Funs arities;
alias SumOfReturns!Funs returns;
foreach(i, Fun; Funs) {
enum firstParam = arities[i];
enum lastParam = firstParam + arity!(Fun);
static if (returns[i] != returns[i+1])
result.field[returns[i]] = Fun(params[firstParam..lastParam]);
}
return result;
}
}
unittest
{
int foo(int i) { return i*i;} // int -> int
int bar() { return 0;} // () -> int
void baz(string s) {} // string -> ()
double[] quux(double d, double[] f) // (double,double[]) -> double[]
{ return f ~ d;}
alias juxtapose!(foo,bar,baz,quux) jux; // jux takes (int,string, double, double[]), returns Tuple!(int,int,double[]);
auto ir = [0,1,2,3,4,5];
auto sr = ["abc", "def","ghijk"];
auto dr = [3.14,2.78,1.00,-1.414];
auto fr = [[0.1,0.2], [0.0,-1.0,-2.0]];
auto m = tmap!jux(ir,sr,dr,fr);
}
/+
template juxtapose2(F...)
{
Tuple!(ReturnTypes!F) juxtapose2(Tuple!(ParameterTypeTuples!F) params) {
typeof(return) result;
alias SumOfArities!F arities;
foreach(i, Unused; F) {
enum firstParam = arities[i];
enum lastParam = firstParam + arity!(F[i]);
result.field[i] = F[i](params.expand[firstParam..lastParam]);
}
return result;
}
}
+/
template isNotVoid(T)
{
enum bool isNotVoid = !is(T == void);
}
struct FlipnR(alias fun)
{
size_t n;
typeof(fun(R.init, 0)) opCall(R)(R r) if (isForwardRange!R)// && is(typeof(fun(r,n))))
{
return fun(r,n);
}
}
/**
Flip and curry range functions, like $(M take), $(M drop), etc. These take a range and a size_t arguments, like $(M take(r,3)), etc.
But sometimes, you just want to create a curried function that will act on any range.
Example:
----
alias flipn!take takeN; // takeN is a generic function, waiting for a number of elements to take.
auto take3 = takeN(3); // take3 is a generic function, taking 3 elements on any range (returns take(range,3))
auto threes = map!take3([[0,1,2,3,4,5],[6,7,8,9], [10]]); // get the first three elements of each range
auto witness = [[0,1,2], [6,7,8], [10]];
foreach(i, elem; witness) {assert(equal(elem, threes.front)); threes.popFront;}
----
*/
FlipnR!fun flipn(alias fun)(size_t n)
{
FlipnR!(fun) tnr;
tnr.n = n;
return tnr;
}
unittest
{
auto rr = [[0,1,2,3,4,5],[6,7,8,9], [10]];
alias flipn!take takeN; // takeN is a higher-order function, waiting for a number of elements to take.
auto take3 = takeN(3); // take3 is a generic function, taking 3 elements on any range (returns take(range,3))
auto threes = map!take3(rr); // get the first three elements of each range
auto witness = [[0,1,2],[6,7,8],[10]];
foreach(elem; witness)
{
assert(equal(elem, threes.front));
threes.popFront;
}
auto take0 = takeN(0);
auto zeroes = map!take0(rr);
foreach(elem; zeroes) assert(elem.empty);
auto take100 = takeN(100);
auto all = map!take100(rr);
foreach(elem; rr) {assert(equal(elem, all.front)); all.popFront;}
}
/**
Flips (reverses) the arguments of a function. It also works for template functions, even
variadic ones. Do not use it on standard variadic functions, though.
Example:
----
int sub(int i, int j) { return i-j;}
int one(int i) { return i;}
double three(double a, int b, string c) { return a;}
alias flip!sub fsub;
alias flip!one fone;
alias flip!three fthree;
assert(fsub(1,2) == sub(2,1));
assert(fone(1) == one(1));
assert(fthree("abc", 0, 3.14) == three(3.14, 0, "abc"));
string conj(A,B)(A a, B b)
{
return to!string(a)~to!string(b);
}
string conjAll(A...)(A a) // variadic template function
{
string result;
foreach(i,elem;a) result ~= to!string(elem);
return result;
}
alias flip!conj fconj;
alias flip!conjAll fconjAll;
assert(fconj(1,2) == "21");
assert(fconjAll(1,2,3,4) == "4321");
----
*/
template flip(alias fun)
{
static if (isFunctionType!(typeof(fun)))
ReturnType!fun flip(ReverseTypes!(ParameterTypeTuple!fun) rargs)
{
return fun(reverseTuple(tuple(rargs)).expand);
}
else
typeof(fun(Init!(ReverseTypes!T))) flip(T...)(T rargs)
{
return fun(reverseTuple(tuple(rargs)).expand);
}
}
version(unittest)
{
string conj(A,B)(A a, B b)
{
return to!string(a)~to!string(b);
}
string conjAll(A...)(A a)
{
string result;
foreach(i,elem;a) result ~= to!string(elem);
return result;
}
}
unittest
{
int sub(int i, int j) { return i-j;}
int one(int i) { return i;}
int none() { return 0;}
double three(double a, int b, string c) { return a;}
alias flip!sub fsub;
alias flip!one fone;
alias flip!none fnone;
alias flip!three fthree;
assert(fsub(1,2) == sub(2,1));
assert(fone(1) == one(1));
assert(fnone() == none());
assert(fthree("abc", 0, 3.14) == three(3.14, 0, "abc"));
alias flip!conj fconj;
alias flip!conjAll fconjAll;
assert(fconj(1,2) == "21");
assert(fconjAll(1,2,3,4) == "4321");
}
/**
Takes a D function, and curries it (in the Haskell sense, not as Phobos' $(M std.functional._curry)): given
a n-args function, it creates n 1-arg functions nested inside one another. When
all original arguments are reached, it returns the result. It's useful to make 'incomplete'
functions to be completed by ranges elements.
Example:
----
int add(int i, int j) { return i+j;}
alias curry!add cadd; // cadd waits for an int, will return an int delegate(int)
auto add3 = cadd(3); // add3 is a function that take an int and return this int + 3.
auto m = map!add3([0,1,2,3]);
assert(equal(m, [3,4,5,6]));
bool equals(int i, int j) { return i==j;}
alias curry!equals cequals;
auto equals4 = cequals(4); // equals4 is a function taking an int and return true iff this int is 4.
auto f = filter!equals4([2,3,4,5,4,3,2,2,3,4]);
assert(equal(f, [4,4,4]));
----
What's fun is that it'll work for template functions too.
Example:
----
string conj(A, B)(A a, B b)
{
return to!string(a)~to!string(b);
}
alias curry!conj cconj;
auto c1 = cconj(1); // c1 is a template function waiting for any type.
assert(c1('a') == "1a");
----
BUG:
for now, it does not verify the compatibility of types while you give it the arguments. It's only
at the end that it sees whether or not it can call the function with these arguments.
Example:
----
// given a function like this, with dependencies between the arguments' types:
A foo(A,B,C)(A a, Tuple!(B,A) b, Tuple!(C,B,A) c) { return a+b.field[1]+c.field[2];}
// if you curries it and gives it an int as first argument, the returned template function should really be:
int foo2(B,C)(Tuple!(B,int) b) { return anotherFunction;}
// because we now know A to be an int...
----
*/
template curry(alias fun)
{
static if (isFunction!fun)
enum curry = mixin(curryImpl!(fun, "", ParameterTypeTuple!fun));
else // template function
enum curry = curriedFunction!(fun)();
}
template curryImpl(alias fun, string xs, T...)
{
static if (T.length == 0)
enum curryImpl = "&fun";
else static if (T.length == 1)
enum curryImpl = "(" ~ T[0].stringof ~ " x1) { return fun(" ~ xs ~ "x1);}";
else
enum curryImpl = "(" ~ T[0].stringof ~ " x" ~ to!string(T.length) ~ ") { return "
~ curryImpl!(fun,xs ~ "x" ~ to!string(T.length) ~ ", ", T[1..$]) ~ ";}";
}
struct CurriedFunction(alias fun, T...) /+if (T.length)+/
{
T _t;
static if (T.length)
void initialize(T t) { _t = t;}
template OpCallType(U...)
{
static if (is (typeof(fun(Init!T, Init!U))))
alias typeof(fun(Init!T, Init!U)) OpCallType;
else
alias CurriedFunction!(fun, T, U) OpCallType;
}
OpCallType!U opCall(U...)(U u)
{
static if(is(typeof(fun(_t, u))))
return fun(_t,u);
else
{
CurriedFunction!(fun, T, U) cf;
static if (U.length) cf.initialize(_t, u);
return cf;
}
}
}
CurriedFunction!(fun, TypeTuple!()) curriedFunction(alias fun)()
{
CurriedFunction!(fun, TypeTuple!()) cf;
return cf;
}
unittest
{
int add(int i, int j) { return i+j;}
alias curry!add cadd; // cadd waits for an int, will return an int delegate(int)
auto add3 = cadd(3); // add3 is a function that take an int and return this int + 3.
auto m = map!add3([0,1,2,3]);
assert(equal(m, [3,4,5,6]));
bool equals(int i, int j) { return i==j;}
alias curry!equals cequals;
auto equals4 = cequals(4); // equals4 is a function taking an int and return true iff this int is 4.
auto f = filter!equals4([2,3,4,5,4,3,2,2,3,4]);
assert(equal(f, [4,4,4]));
}
struct InvertibleFun(A, B)
{
B delegate(A) fun;
A delegate(B) funInv;
AB!(A,B,T) opCall(T)(T t) if (is(T == A) || is(T == B))
{
static if (is(T == A))
return fun(t);
else
return funInv(t);
}
}
/**
Takes two delegates: one from $(M A) to $(M B), the other from $(M B) to $(M A). $(M A) and $(M B) must be different types.
The functions are supposed to be the inverse of one another (that is: f(g(x)) == x), but that's not checked.
$(M _invertibleFun) is then a function that accepts either a $(M A) or a $(M B) and then returns a $(M B) or a $(M A).
*/
InvertibleFun!(A,B) invertibleFun(A, B)(B delegate(A) fun, A delegate(B) funInv)
{
InvertibleFun!(A,B) ifun;
ifun.fun = fun;
ifun.funInv = funInv;
return ifun;
}
struct Apply(T...)
{
T value;
typeof(F.init(Init!T)) opCall(F)(F fun)
{
return fun(value);
}
}
/**
Takes a value argument and creates a function (in fact, a struct with an opCall) that will accept any delegate
and _apply it to the original value. It's useful when you want to map a certain value on a range of functions:
just map $(M _apply!value) to the range.
Example:
----
int f0(int i) { return i;}
int f1(int i) { return i*i;}
int f2(int i) { return i*i*i;}
auto apply4 = apply(4); // will call any function with '4' as argument.
auto rangeFun = [&f0, &f1, &f2];
auto map4 = map!apply4(rangeFun);
assert(equal(map4, [4, 4*4, 4*4*4]));
// This works for n-args functions too:
double g0(int i, double d) { return i+d;}
auto apply123 = apply(1, 2.30);
assert(apply123(&g0) == 3.30);
----
*/
Apply!T apply(T...)(T value)
{
Apply!T app;
foreach(i, Type; T) app.value[i] = value[i];
return app;
}
unittest
{
int f0(int i) { return i;}
int f1(int i) { return i*i;}
int f2(int i) { return i*i*i;}
auto apply4 = apply(4); // will call any function with '4' as argument.
auto rangeFun = [&f0, &f1, &f2];
auto map4 = map!apply4(rangeFun);
assert(equal(map4, [4, 4*4, 4*4*4]));
// This works for n-args functions too:
double g0(int i, double d) { return i+d;}
auto apply123 = apply(1, 2.30);
assert(apply123(&g0) == 3.30);
}
/**
Transforms a standard function into a destructuring one. Given:
----
int foo(int a, int b, int c) {}
----
then, $(M _destructured!foo) is a function that accepts three $(M int)s as arguments, but also $(M Tuple!(int,int,int))
or $(M int[]) or $(M int[3]) or even any class $(M C) or struct $(M S) if $(M C.tupleof)/$(M S.tupleof) gives three $(M int)s. In effect,
$(M _destructured!foo) will try to destructure (decompose, crack open, if you will) anything passed to it, to find three $(M int)s in a row to give
to $(M foo).
Note: It's still 'in construction', as it depends on the $(M __()) function from $(M dranges.reftuple). The doc
should be extended.
TODO: also if t is itself a tuple __(params) = t;
*/
template destructured(alias fun)
{
ReturnType!fun destructured(T...)(T t)
if(__traits(compiles, {
ParameterTypeTuple!fun params;
_(params) = tuple(t);
return fun(params);
}))
{
ParameterTypeTuple!fun params;
_(params) = tuple(t);
return fun(params);
}
}
/**
Transforms a function $(M foo) taking a $(M T) into a function accepting a $(M T[]) as an argument
and which applies $(M foo) to each element of the array, returning the resulting array.
Example:
----
int foo(int i) { return i*i;}
alias mapper!foo mfoo;
assert(mfoo([0,1,2,3,4]) == [0,1,4,9,16]);
----
If $(M foo) takes more than one argument, $(M _mapper!foo) waits for a $(M Tuple!(Args)[]) or accepts
a variadic number of arguments, as long as the types and their numbers correspond.
Example:
----
int bar(int i, double j, string s) { return (to!int(i*j));}
alias mapper!bar mbar;
assert(mbar(1,3.14,"ab", 2,-0.5,"hello!", 0,0,"") == [3,-3,0]);
----
TODO: expand tuples [tuple(a,b), tuple(a,b), ...]
*/
template mapper(alias fun)
{
auto mapper(T...)(T args) {
static if (T.length >1 || (T.length == 1 && !isDynamicArray!(T[0]))) // args as tuple
{
static if (is(ParameterTypeTuple!fun)
&& (ParameterTypeTuple!fun).length > 1
&& T.length % (ParameterTypeTuple!fun).length == 0) // more than one param
{
enum nargs = (ParameterTypeTuple!fun).length;
ReturnType!fun[] result = new ReturnType!fun[T.length / nargs];
foreach(i, Arg; T) {
static if (i % nargs == 0) result[i/nargs] = fun(args[i..i+nargs]);
}
return result;
}
else // one param or we cannot determine it (template function, for example)
{
alias typeof(fun(CommonType!T.init)) RT;
RT[] result = new RT[args.length];
foreach(i,Arg; T) result[i] = fun(args[i]);
return result;
}
}
else // args as array
{
alias typeof(fun(T[0][0].init)) RT;
RT[] result = new RT[args[0].length];
foreach(i,arg; args[0]) result[i] = fun(arg);
return result;
}
}
}
unittest
{
int foo(int i) { return i*i;}
alias mapper!foo mfoo;
assert(mfoo([0,1,2,3,4]) == [0,1,4,9,16]);
int bar(int i, double j, string s) { return (to!int(i*j));}
alias mapper!bar mbar;
assert(mbar(1,3.14,"ab", 2,-1.5,"hello!", 0,0,"") == [3,-3,0]);
}
/**
Transforms a function $(M foo) accepting a $(M T) into a function accepting
a $(M Tuple!(T,T,T,...T)) (or any tuple with compatible types). It will apply
$(M foo) to all elements of the tuple and return the tuple of these results.
Example:
----
int foo(int i) { return i*i;}
alias tupler!foo tfoo;
auto t = tuple(0,1,2,3,4);
assert(tfoo(t) == tuple(0,1,4,9,16));
----
*/
template tupler(alias fun)
{
auto tupler(T)(T tup) if (is(typeof(fun(CommonType!(T.Types).init))))
{
alias typeof(fun(CommonType!(T.Types).init)) RT;
alias TypeNuple!(RT, T.Types.length) TRT;
TRT result;
foreach(i, Type; TRT) result[i] = fun(tup.field[i]);
return tuple(result);
}
}
unittest
{
int foo(int i) { return i*i;}
alias tupler!foo tfoo;
auto t = tuple(0,1,2,3,4);
assert(tfoo(t) == tuple(0,1,4,9,16));
}
/// The void function: takes any arguments, returns $(M void).
void voidFun(...) {}
/// The _null function: takes no argument, returns $(M void).
void nullFun() {}
/**
Takes any value, returns a constant function: one that accepts any arguments and will always return
the initial value. If called with no argument, it will produce the equivalent of $(M voidFun).
Example:
----
auto one = constantFun(1);
assert(equal(map!one(["a","b","abc"]), [1,1,1]));
----
*/
T[0] delegate(...) constantFun(T...)(T t) if (T.length == 1)
{
return (...) { return t[0];};
}
/// ditto
Tuple!T delegate(...) constantFun(T...)(T t) if (T.length > 1)
{
return (...) { return tuple(t);};
}
/// ditto
void delegate(...) constantFun(T...)(T t) if (T.length == 0)
{
return (...) { return;};
}
unittest
{
auto one = constantFun(1);
assert(equal(map!one(["a","b","abc"]), [1,1,1]));
}
//template ExtendFunType(alias fun, T...)
//{
// static if (is(typeof(fun(T.init))))
// alias typeof(fun(T.init)) ExtendFunType;
// else
// alias T[0] ExtendFunType;
//}
struct ExtendFun(alias fun)
{
auto opCall(T...)(T t)
{
static if ( isFunction!fun && is(ParameterTypeTuple!fun) && is(ParameterTypeTuple!fun == TypeTuple!T) ) // non-templated function
return fun(t);
// else static if (is(typeof(fun) == string) && is(typeof( naryFun!fun(t) ))) // templated function
// return naryFun!fun(t);
else
return t[0];
}
}
/**
Takes a function $(M foo) and 'extends' it, allowing it to accept any type of argument.
If the arguments types are compatible with $(M foo), returns foo(args) otherwise, it just returns
the argument.
That may seem a strange template to define, but it's quite useful for mapping a tuple (see $(M dranges.tuple.mapTuple)
and $(M dranges.tupletree.mapTree)).
Suppose you have a tuple and want to change only the strings in it. Define $(M foo) to act on strings, extend it with
$(M _extendFun!foo) and voila, you can then map $(M _extendFun!foo) on your tuple: the strings will be transformed, leaving the
other types untouched. I learnt the trick from a Haskell article.
Example:
----
import dranges.tuple;
auto t = tuple("bin", 1024, 3.14159,
"src", 0, 1.0,
"myDirectory/foo", 100, -2.3);
string foo(string s) { return "std/" ~ s;}
auto efoo = extendFun!foo; // beware: it's not alias extendFun!foo efoo;, as for other templates around here.
auto t2 = mapTuple ! efoo (t);
assert(t2 == tuple("std/bin", 1024, 3.14159,
"std/src", 0, 1.0,
"std/myDirectory/foo", 100, -2.3));
----
*/
//ExtendFun!fun extendFun(alias fun)()
//{
// ExtendFun!(fun) efun;
// return efun;
//}
template extendFun(alias fun)
{
auto extendFun(T...)(T t)
{
alias naryFun!fun nfun;
static if (is(typeof(nfun(t))))
return nfun(t);
else
return t[0];
}
}
version(unittest)
{
import dranges.tuple;
string foo(string s) { return "std/" ~ s;}
}
unittest
{
auto t = tuple("bin", 1024, 3.14159,
"src", 0, 1.0,
"myDirectory/foo", 100, -2.3);
auto efoo = extendFun!foo;
auto t2 = mapTuple ! efoo (t);
assert(t2 == tuple("std/bin", 1024, 3.14159,
"std/src", 0, 1.0,
"std/myDirectory/foo", 100, -2.3));
}
struct ExtendFun0(alias fun, D)
{
D defaultValue;
typeof(fun(Init!T)) opCall(T...)(T t) if (is(typeof(fun(t))))
{
return fun(t);
}
D opCall(T...)(T t) if (!is(typeof(fun(t))))
{
return defaultValue;
}
}
/**
Same as before, but with a default value returned when extendFun is offered
an arg that $(M foo) cannot accept. The default value can be of any type.
Example:
----
import dranges.tuple;
auto t = tuple("bin", 1024, 3.14159,
"src", 0, 1.0,
"myDirectory/foo", 100, -2.3);
string foo(string s) { return "std/" ~ s;}
auto efoo = extendFun0!foo(0);
auto t2 = mapTuple ! efoo (t);
assert(t2 == tuple("std/bin", 0, 0,
"std/src", 0, 0,
"std/myDirectory/foo", 0, 0));
----
*/
ExtendFun0!(fun, D) extendFun0(alias fun, D)(D defaultValue)
{
ExtendFun0!(fun,D) efun;
efun.defaultValue = defaultValue;
return efun;
}
unittest
{
auto t = tuple("bin", 1024, 3.14159,
"src", 0, 1.0,
"myDirectory/foo", 100, -2.3);
auto efoo0 = extendFun0!foo(0); // foo is defined in a version(unittest) statement higher up in the code
auto t2 = mapTuple ! efoo0 (t);
assert(t2 == tuple("std/bin", 0, 0,
"std/src", 0, 0,
"std/myDirectory/foo", 0, 0));
}
/**
This is just a wrapper around the $(M match) function found in $(M dranges.patternmatch), here to emphasize
the way $(M match) is just a many-types-to-many-types 'function'. Explained a bit more clearly, $(M _eitherFun)
takes any number of functions and keep them near its hot little heart. When passed an argument, it will
successively test each function and returns the result of the first one that matches. No match means it will
throw a NoMatch exception. Functions are tested the same order they were passed as arguments.
How is this different from overloading, will you ask? I'm glad you did:
$(UL
$(LI first, you can use it to 'group' many different functions, from different origins and different names.)
$(LI second (and that may be the most important point), it's a template, so the return
type of $(M _eitherFun) can be different for each argument type. So you can use it to map a range, but also a tuple, with $(M dranges.tuple.mapTuple).)
$(LI third, it accepts template functions. In fact, it even accepts 'string' functions, as in "a+b*c-d.expand". See the $(M patternmatch)
module documentation for more explanations.)
$(LI fourth, once it's defined, you can pass it around as one entity. Most notably, it can becomes the argument
of another meta-function there or even the argument to another $(M _eitherFun!))
)
So, in functional languages terms, it's a sum of functions (just as $(M juxtapose) is a product).
Example:
----
int f1(int i) { return i;}
double f2(double d) { return d*d;}
int f3(int i, string s) { return i;}
string f4(string s, int i) { return s;}
alias eitherFun!(f1,f2,f3,f4) efun; // efun accepts either an int, or a double, or a (int,string) or a (string, int)
assert(efun(1) == 1);
assert(efun(1.5) == 2.25);
assert(efun(1,"abc") == 1);
assert(efun("abc",1) == "abc");
// Let's extend it, then.
int[] f5(int[] i) { return i.reverse;}
alias eitherFun!(efun, f5) efun5; // efun5 will test f1, then f2, ... and f5 at last resort.
// alias eitherFun(f5, efun) efun5bis would have tested f5 first, then f1, ...
assert(efun5(1) == 1); // efun5 is like efun
assert(efun5(1.5) == 2.25);
assert(efun5(1,"abc") == 1);
assert(efun5("abc",1) == "abc");
assert(efun5([0,1,2]) == [2,1,0]); // except it also accepts an array of ints as argument.
----
Note: as said before, functions are tested in the same order they were passed as arguments. So a function can 'swallow' arguments
that could have been accepted by another, downstream function.
*/
template eitherFun(F...)
{
alias match!(StaticMap!(naryFun, F)) eitherFun;
}
unittest
{
int f1(int i) { return i;}
double f2(double d) { return d*d;}
int f3(int i, string s) { return i;}
string f4(string s, int i) { return s;}
int[] f5(int[] i) { return i.reverse;}
alias eitherFun!(f1,f2,f3,f4) efun;
assert(efun(1) == 1);
assert(efun(1.5) == 2.25);
assert(efun(1,"abc") == 1);
assert(efun("abc",1) == "abc");
alias eitherFun!(efun, f5) efun5;
assert(efun5(1) == 1);
assert(efun5(1.5) == 2.25);
assert(efun5(1,"abc") == 1);
assert(efun5("abc",1) == "abc");
assert(efun5([0,1,2]) == [2,1,0]);
}
/**
A simple adapter, when you have a complicated function you do not want to touch (or cannot) touch. It
applies the $(M pre) preprocessing to the arguments, calls fun and then postprocess the result. The
default for post is "a", that is the identity string function. So the two args version of $(M _adaptFun)
just deals with adapting the arguments.
*/
template adaptFun(alias pre, alias fun, alias post = "a")
{
typeof(naryFun!post(naryFun!fun(naryFun!pre(Init!T)))) adaptFun(T...)(T t)
{
return naryFun!post(naryFun!fun(naryFun!pre(t)));
}
}
/**
The composition 'power' of a function: $(M fun(fun(fun(x)...))), n times. n == 1 is the same
as $(M fun) and n = 0 is the identity function (just returns the arguments).
Example:
----
int inc(int i) { return i+1;}
string conc(string s) { return s ~ s;}
alias powerFun!(inc, 5) plus5; // calls inc(inc(inc(inc(inc(t))))), so returns t+5
alias powerFun!(inc, 1) plus1;
alias powerFun!(inc, 0) plus0;
assert(plus5(4) == 9);
assert(plus1(4) == 5);
assert(plus0(4) == 4);
alias powerFun!(conc, 2) conc2;
assert(conc("abc") == "abcabc");
assert(conc2("abc") == "abcabcabcabc");
assert(conc2("abc") == conc(conc("abc")));
----
*/
template powerFun(alias fun, size_t n)
{