File: functional.d

package info (click to toggle)
mir-core 1.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 560 kB
  • sloc: makefile: 9; sh: 7
file content (900 lines) | stat: -rw-r--r-- 22,677 bytes parent folder | download
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
/++
Functions that manipulate other functions.
This module provides functions for compile time function composition. These
functions are helpful when constructing predicates for the algorithms in
$(MREF mir, ndslice).
$(BOOKTABLE $(H2 Functions),
$(TR $(TH Function Name) $(TH Description))
    $(TR $(TD $(LREF naryFun))
        $(TD Create a unary, binary or N-nary function from a string. Most often
        used when defining algorithms on ranges and slices.
    ))
    $(TR $(TD $(LREF pipe))
        $(TD Join a couple of functions into one that executes the original
        functions one after the other, using one function's result for the next
        function's argument.
    ))
    $(TR $(TD $(LREF not))
        $(TD Creates a function that negates another.
    ))
    $(TR $(TD $(LREF reverseArgs))
        $(TD Predicate that reverses the order of its arguments.
    ))
    $(TR $(TD $(LREF forward))
        $(TD Forwards function arguments with saving ref-ness.
    ))
    $(TR $(TD $(LREF tuple))
        $(TD Removes $(LREF Ref) shell.
    ))
    $(TR $(TD $(LREF unref))
        $(TD Creates a $(LREF Tuple) structure.
    ))
    $(TR $(TD $(LREF __ref))
        $(TD Creates a $(LREF Ref) structure.
    ))
)
License: $(HTTP www.apache.org/licenses/LICENSE-2.0, Apache-2.0)
Authors: Ilia Ki, $(HTTP erdani.org, Andrei Alexandrescu (some original code from std.functional))

Macros:
NDSLICE = $(REF_ALTTEXT $(TT $2), $2, mir, ndslice, $1)$(NBSP)
+/
module mir.functional;

private enum isRef(T) = is(T : Ref!T0, T0);

import mir.math.common: optmath;

public import core.lifetime : forward;

@optmath:

/++
Constructs static array.
+/
T[N] staticArray(T, size_t N)(return scope T[N] a...) {
    import std.traits: isDynamicArray;
    static if (isDynamicArray!T) {  
        T[N] ret;
        static foreach(i; 0..a.length) ret[i] = a[i];
        return ret;
    }
    else return a;
}

@safe version(mir_core_test) unittest
{
    string[2] v = ["AA", "BB"];
    auto res = staticArray(v);
    assert(res == v);
}

/++
Simple wrapper that holds a pointer.
It is used for as workaround to return multiple auto ref values.
+/
struct Ref(T)
    if (!isRef!T)
{
    @optmath:

    @disable this();
    ///
    this(ref T value) @trusted
    {
        __ptr = &value;
    }
    ///
    T* __ptr;
    ///
    ref inout(T) __value() inout @property { return *__ptr; }
    ///
    alias __value this;

    ///
    bool opEquals(ref scope const T rhs) const scope
    {
        return __value == rhs;
    }

    ///
    bool opEquals(scope const T rhs) const scope
    {
        return __value == rhs;
    }

    static if (__traits(hasMember, T, "toHash") || __traits(isScalar, T))
    ///
    size_t toHash() const
    {
        return hashOf(__value);
    }
}

/// Creates $(LREF Ref) wrapper.
Ref!T _ref(T)(ref T value)
{
    return Ref!T(value);
}

private mixin template _RefTupleMixin(T...)
    if (T.length <= 26)
{
    static if (T.length)
    {
        enum i = T.length - 1;
        static if (isRef!(T[i]))
            mixin(`@optmath @property ref ` ~ cast(char)('a' + i) ~ `() { return *expand[` ~ i.stringof ~ `].__ptr; }` );
        else
            mixin(`alias ` ~ cast(char)('a' + i) ~ ` = expand[` ~ i.stringof ~ `];`);
        mixin ._RefTupleMixin!(T[0 .. $-1]);
    }
}

/++
Simplified tuple structure. Some fields may be type of $(LREF Ref).
Ref stores a pointer to a values.
+/
struct Tuple(T...)
{
    @optmath:
    T expand;
    alias expand this;
    mixin _RefTupleMixin!T;
}

deprecated("Use 'Tuple' instead")
alias RefTuple = Tuple;

/// Removes $(LREF Ref) shell.
alias Unref(V : Ref!T, T) = T;
/// ditto
template Unref(V : Tuple!T, T...)
{
    import std.meta: staticMap;
    alias Unref = Tuple!(staticMap!(.Unref, T));
}

/// ditto
alias Unref(V) = V;

/++
Returns: a $(LREF Tuple) structure.
+/
Tuple!Args tuple(Args...)(auto ref Args args)
{
    return Tuple!Args(args);
}

deprecated("Use 'tuple' instead")
alias refTuple = tuple;

/// Removes $(LREF Ref) shell.
ref T unref(V : Ref!T, T)(scope return V value)
{
    return *value.__ptr;
}

/// ditto
Unref!(Tuple!T) unref(V : Tuple!T, T...)(V value)
{
    typeof(return) ret;
    foreach(i, ref elem; ret.expand)
        elem = unref(value.expand[i]);
    return ret;
}

/// ditto
ref V unref(V)(scope return ref V value)
{
    return value;
}

/// ditto
V unref(V)(V value)
{
    import std.traits: hasElaborateAssign;
    static if (hasElaborateAssign!V)
    {
        import core.lifetime: move;
        return move(value);
    }
    else
        return value;
}

private template autoExpandAndForwardElem(alias value)
{

}

template autoExpandAndForward(alias value)
    if (is(typeof(value) : Tuple!Types, Types...))
{

    import core.lifetime: move;
    enum isLazy = __traits(isRef,  value) || __traits(isOut,  value) || __traits(isLazy, value);
    template autoExpandAndForwardElem(size_t i)
    {
        alias T = typeof(value.expand[i]);
        static if (isRef!T)
        {
            ref autoExpandAndForwardElem()
            {
                return *value.expand[i].__ptr;
            }
        }
        else
        {
            static if (isLazy)
                @property ref autoExpandAndForwardElem(){ pragma(inline, true); return value.expand[i]; }
            else
            static if (is(typeof(move(value.expand[i]))))
                @property auto autoExpandAndForwardElem(){ pragma(inline, true); return move(value.expand[i]); }
            else
                @property auto autoExpandAndForwardElem(){ pragma(inline, true); return value.expand[i]; }
        }
    }

    import mir.internal.utility: Iota;
    import std.meta: staticMap;
    alias autoExpandAndForward = staticMap!(autoExpandAndForwardElem, Iota!(value.expand.length));
}

version(mir_core_test) unittest
{
    long v;
    auto tup = tuple(v._ref, 2.3);

    auto f(ref long a, double b)
    {
        assert(b == 2.3);
        assert(a == v);
        assert(&a == &v);
    }

    f(autoExpandAndForward!tup);
}

private string joinStrings()(string[] strs)
{
    if (strs.length)
    {
        auto ret = strs[0];
        foreach(s; strs[1 .. $])
            ret ~= s;
        return ret;
    }
    return null;
}

private auto copyArg(alias a)()
{
    return a;
}

/++
Takes multiple functions and adjoins them together. The result is a
$(LREF Tuple) with one element per passed-in function. Upon
invocation, the returned tuple is the adjoined results of all
functions.
Note: In the special case where only a single function is provided
(`F.length == 1`), adjoin simply aliases to the single passed function
(`F[0]`).
+/
template adjoin(fun...) if (fun.length && fun.length <= 26)
{
    static if (fun.length != 1)
    {
        import std.meta: staticMap, Filter;
        static if (Filter!(_needNary, fun).length == 0)
        {
            ///
            @optmath auto adjoin(Args...)(auto ref Args args)
            {
                template _adjoin(size_t i)
                {
                    static if (__traits(compiles, &(fun[i](forward!args))))
                        enum _adjoin = "Ref!(typeof(fun[" ~ i.stringof ~ "](forward!args)))(fun[" ~ i.stringof ~ "](args)), ";
                    else
                        enum _adjoin = "fun[" ~ i.stringof ~ "](args), ";
                }

                import mir.internal.utility;
                mixin("return tuple(" ~ [staticMap!(_adjoin, Iota!(fun.length))].joinStrings ~ ");");
            }
        }
        else alias adjoin = .adjoin!(staticMap!(naryFun, fun));
    }
    else alias adjoin = naryFun!(fun[0]);
}

///
@safe version(mir_core_test) unittest
{
    static bool f1(int a) { return a != 0; }
    static int f2(int a) { return a / 2; }
    auto x = adjoin!(f1, f2)(5);
    assert(is(typeof(x) == Tuple!(bool, int)));
    assert(x.a == true && x.b == 2);
}

@safe version(mir_core_test) unittest
{
    alias f = pipe!(adjoin!("a", "a * a"), "a[0]");
    static assert(is(typeof(f(3)) == int));
    auto d = 4;
    static assert(is(typeof(f(d)) == Ref!int));
}

@safe version(mir_core_test) unittest
{
    static bool F1(int a) { return a != 0; }
    auto x1 = adjoin!(F1)(5);
    static int F2(int a) { return a / 2; }
    auto x2 = adjoin!(F1, F2)(5);
    assert(is(typeof(x2) == Tuple!(bool, int)));
    assert(x2.a && x2.b == 2);
    auto x3 = adjoin!(F1, F2, F2)(5);
    assert(is(typeof(x3) == Tuple!(bool, int, int)));
    assert(x3.a && x3.b == 2 && x3.c == 2);

    bool F4(int a) { return a != x1; }
    alias eff4 = adjoin!(F4);
    static struct S
    {
        bool delegate(int) @safe store;
        int fun() { return 42 + store(5); }
    }
    S s;
    s.store = (int a) { return eff4(a); };
    auto x4 = s.fun();
    assert(x4 == 43);
}

//@safe
version(mir_core_test) unittest
{
    import std.meta: staticMap;
    alias funs = staticMap!(naryFun, "a", "a * 2", "a * 3", "a * a", "-a");
    alias afun = adjoin!funs;
    int a = 5, b = 5;
    assert(afun(a) == tuple(Ref!int(a), 10, 15, 25, -5));
    assert(afun(a) == tuple(Ref!int(b), 10, 15, 25, -5));

    static class C{}
    alias IC = immutable(C);
    IC foo(){return typeof(return).init;}
    Tuple!(IC, IC, IC, IC) ret1 = adjoin!(foo, foo, foo, foo)();

    static struct S{int* p;}
    alias IS = immutable(S);
    IS bar(){return typeof(return).init;}
    enum Tuple!(IS, IS, IS, IS) ret2 = adjoin!(bar, bar, bar, bar)();
}

private template needOpCallAlias(alias fun)
{
    /* Determine whether or not naryFun need to alias to fun or
     * fun.opCall. Basically, fun is a function object if fun(...) compiles. We
     * want is(naryFun!fun) (resp., is(naryFun!fun)) to be true if fun is
     * any function object. There are 4 possible cases:
     *
     *  1) fun is the type of a function object with static opCall;
     *  2) fun is an instance of a function object with static opCall;
     *  3) fun is the type of a function object with non-static opCall;
     *  4) fun is an instance of a function object with non-static opCall.
     *
     * In case (1), is(naryFun!fun) should compile, but does not if naryFun
     * aliases itself to fun, because typeof(fun) is an error when fun itself
     * is a type. So it must be aliased to fun.opCall instead. All other cases
     * should be aliased to fun directly.
     */
    static if (is(typeof(fun.opCall) == function))
    {
        import std.traits: Parameters;
        enum needOpCallAlias = !is(typeof(fun)) && __traits(compiles, () {
            return fun(Parameters!fun.init);
        });
    }
    else
        enum needOpCallAlias = false;
}

private template _naryAliases(size_t n)
    if (n <= 26)
{
    static if (n == 0)
        enum _naryAliases = "";
    else
    {
        enum i = n - 1;
        enum _naryAliases = _naryAliases!i ~ "alias " ~ cast(char)('a' + i) ~ " = args[" ~ i.stringof ~ "];\n";
    }
}

private template stringFun(string fun)
{
    /// Specialization for string lambdas
    @optmath auto ref stringFun(Args...)(auto ref Args args)
        if (args.length <= 26 && (Args.length == 0) == (fun.length == 0))
    {
        import mir.math.common;
        static if (fun.length)
        {
            mixin(_naryAliases!(Args.length));
            return mixin(fun);
        }
        else
        {
            return;
        }
    }
}

/++
Aliases itself to a set of functions.

Transforms strings representing an expression into a binary function. The
strings must use symbol names `a`, `b`, ..., `z`  as the parameters.
If `functions[i]` is not a string, `naryFun` aliases itself away to `functions[i]`.
+/
template naryFun(functions...)
    if (functions.length >= 1)
{
    static foreach (fun; functions)
    {
        static if (is(typeof(fun) : string))
        {
            alias naryFun = stringFun!fun;
        }
        else static if (needOpCallAlias!fun)
            alias naryFun = fun.opCall;
        else
            alias naryFun = fun;
    }
}

///
@safe version(mir_core_test) unittest
{
    // Strings are compiled into functions:
    alias isEven = naryFun!("(a & 1) == 0");
    assert(isEven(2) && !isEven(1));
}

///
@safe version(mir_core_test) unittest
{
    alias less = naryFun!("a < b");
    assert(less(1, 2) && !less(2, 1));
    alias greater = naryFun!("a > b");
    assert(!greater("1", "2") && greater("2", "1"));
}

/// `naryFun` accepts up to 26 arguments.
@safe version(mir_core_test) unittest
{
    assert(naryFun!("a * b + c")(2, 3, 4) == 10);
}

/// `naryFun` can return by reference.
version(mir_core_test) unittest
{
    int a;
    assert(&naryFun!("a")(a) == &a);
}

/// `args` parameter tuple
version(mir_core_test) unittest
{
    assert(naryFun!("args[0] + args[1]")(2, 3) == 5);
}

/// Multiple functions
@safe pure nothrow @nogc
version(mir_core_test) unittest
{
    alias fun = naryFun!(
        (uint a) => a,
        (ulong a) => a * 2,
        a => a * 3,
    );

    int a = 10;
    long b = 10;
    float c = 10;

    assert(fun(a) == 10);
    assert(fun(b) == 20);
    assert(fun(c) == 30);
}

@safe version(mir_core_test) unittest
{
    static int f1(int a) { return a + 1; }
    static assert(is(typeof(naryFun!(f1)(1)) == int));
    assert(naryFun!(f1)(41) == 42);
    int f2(int a) { return a + 1; }
    static assert(is(typeof(naryFun!(f2)(1)) == int));
    assert(naryFun!(f2)(41) == 42);
    assert(naryFun!("a + 1")(41) == 42);

    int num = 41;
    assert(naryFun!"a + 1"(num) == 42);

    // Issue 9906
    struct Seen
    {
        static bool opCall(int n) { return true; }
    }
    static assert(needOpCallAlias!Seen);
    static assert(is(typeof(naryFun!Seen(1))));
    assert(naryFun!Seen(1));

    Seen s;
    static assert(!needOpCallAlias!s);
    static assert(is(typeof(naryFun!s(1))));
    assert(naryFun!s(1));

    struct FuncObj
    {
        bool opCall(int n) { return true; }
    }
    FuncObj fo;
    static assert(!needOpCallAlias!fo);
    static assert(is(typeof(naryFun!fo)));
    assert(naryFun!fo(1));

    // Function object with non-static opCall can only be called with an
    // instance, not with merely the type.
    static assert(!is(typeof(naryFun!FuncObj)));
}

@safe version(mir_core_test) unittest
{
    static int f1(int a, string b) { return a + 1; }
    static assert(is(typeof(naryFun!(f1)(1, "2")) == int));
    assert(naryFun!(f1)(41, "a") == 42);
    string f2(int a, string b) { return b ~ "2"; }
    static assert(is(typeof(naryFun!(f2)(1, "1")) == string));
    assert(naryFun!(f2)(1, "4") == "42");
    assert(naryFun!("a + b")(41, 1) == 42);
    //@@BUG
    //assert(naryFun!("return a + b;")(41, 1) == 42);

    // Issue 9906
    struct Seen
    {
        static bool opCall(int x, int y) { return true; }
    }
    static assert(is(typeof(naryFun!Seen)));
    assert(naryFun!Seen(1,1));

    struct FuncObj
    {
        bool opCall(int x, int y) { return true; }
    }
    FuncObj fo;
    static assert(!needOpCallAlias!fo);
    static assert(is(typeof(naryFun!fo)));
    assert(naryFun!fo(1,1));

    // Function object with non-static opCall can only be called with an
    // instance, not with merely the type.
    static assert(!is(typeof(naryFun!FuncObj)));
}


/++
N-ary predicate that reverses the order of arguments, e.g., given
`pred(a, b, c)`, returns `pred(c, b, a)`.
+/
template reverseArgs(alias fun)
{
    import std.meta: Reverse;
    ///
    @optmath auto ref reverseArgs(Args...)(auto ref Args args)
        if (is(typeof(fun(Reverse!args))))
    {
        return fun(Reverse!args);
    }

}

///
@safe version(mir_core_test) unittest
{
    int abc(int a, int b, int c) { return a * b + c; }
    alias cba = reverseArgs!abc;
    assert(abc(91, 17, 32) == cba(32, 17, 91));
}

@safe version(mir_core_test) unittest
{
    int a(int a) { return a * 2; }
    alias _a = reverseArgs!a;
    assert(a(2) == _a(2));
}

@safe version(mir_core_test) unittest
{
    int b() { return 4; }
    alias _b = reverseArgs!b;
    assert(b() == _b());
}

@safe version(mir_core_test) unittest
{
    alias gt = reverseArgs!(naryFun!("a < b"));
    assert(gt(2, 1) && !gt(1, 1));
    int x = 42;
    bool xyz(int a, int b) { return a * x < b / x; }
    auto foo = &xyz;
    foo(4, 5);
    alias zyx = reverseArgs!(foo);
    assert(zyx(5, 4) == foo(4, 5));
}

/++
Negates predicate `pred`.
+/
template not(alias pred)
{
    static if (!is(typeof(pred) : string) && !needOpCallAlias!pred)
    ///
    @optmath bool not(T...)(auto ref T args)
    {
        return !pred(args);
    }
    else
        alias not = .not!(naryFun!pred);
}

///
@safe version(mir_core_test) unittest
{
    import std.algorithm.searching : find;
    import std.uni : isWhite;
    string a = "   Hello, world!";
    assert(find!(not!isWhite)(a) == "Hello, world!");
}

@safe version(mir_core_test) unittest
{
    assert(not!"a != 5"(5));
    assert(not!"a != b"(5, 5));

    assert(not!(() => false)());
    assert(not!(a => a != 5)(5));
    assert(not!((a, b) => a != b)(5, 5));
    assert(not!((a, b, c) => a * b * c != 125 )(5, 5, 5));
}

private template _pipe(size_t n)
{
    static if (n)
    {
        enum i = n - 1;
        enum _pipe = "f[" ~ i.stringof ~ "](" ~ ._pipe!i ~ ")";
    }
    else
        enum _pipe = "forward!args";
}

private template _unpipe(alias fun)
{
    import std.traits: TemplateArgsOf, TemplateOf;
    static if (__traits(compiles, TemplateOf!fun))
        static if (__traits(isSame, TemplateOf!fun, .pipe))
            alias _unpipe = TemplateArgsOf!fun;
        else
            alias _unpipe = fun;
    else
        alias _unpipe = fun;

}

private enum _needNary(alias fun) = is(typeof(fun) : string) || needOpCallAlias!fun;

/++
Composes passed-in functions `fun[0], fun[1], ...` returning a
function `f(x)` that in turn returns
`...(fun[1](fun[0](x)))...`. Each function can be a regular
functions, a delegate, a lambda, or a string.
+/
template pipe(fun...)
{
    static if (fun.length != 1)
    {
        import std.meta: staticMap, Filter;
        alias f = staticMap!(_unpipe, fun);
        static if (f.length == fun.length && Filter!(_needNary, f).length == 0)
        {
            ///
            @optmath auto ref pipe(Args...)(auto ref Args args)
            {
                return mixin (_pipe!(fun.length));
            }
        }
        else alias pipe = .pipe!(staticMap!(naryFun, f));
    }
    else alias pipe = naryFun!(fun[0]);
}

///
@safe version(mir_core_test) unittest
{
    assert(pipe!("a + b", a => a * 10)(2, 3) == 50);
}

/// `pipe` can return by reference.
version(mir_core_test) unittest
{
    int a;
    assert(&pipe!("a", "a")(a) == &a);
}

/// Template bloat reduction
version(mir_core_test) unittest
{
    enum  a = "a * 2";
    alias b = e => e + 2;

    alias p0 = pipe!(pipe!(a, b), pipe!(b, a));
    alias p1 = pipe!(a, b, b, a);

    static assert(__traits(isSame, p0, p1));
}

@safe version(mir_core_test) unittest
{
    import std.algorithm.comparison : equal;
    import std.algorithm.iteration : map;
    import std.array : split;
    import std.conv : to;

    // First split a string in whitespace-separated tokens and then
    // convert each token into an integer
    assert(pipe!(split, map!(to!(int)))("1 2 3").equal([1, 2, 3]));
}


struct AliasCall(T, string methodName, TemplateArgs...)
{
    T __this;
    alias __this this;

    ///
    auto lightConst()() const @property
    {
        import mir.qualifier;
        return AliasCall!(LightConstOf!T, methodName, TemplateArgs)(__this.lightConst);
    }

    ///
    auto lightImmutable()() immutable @property
    {
        import mir.qualifier;
        return AliasCall!(LightImmutableOf!T, methodName, TemplateArgs)(__this.lightImmutable);
    }

    this()(auto ref T value)
    {
        __this = value;
    }
    auto ref opCall(Args...)(auto ref Args args)
    {
        import std.traits: TemplateArgsOf;
        mixin("return __this." ~ methodName ~ (TemplateArgs.length ? "!TemplateArgs" : "") ~ "(forward!args);");
    }
}

/++
Replaces call operator (`opCall`) for the value using its method.
The funciton is designed to use with  $(NDSLICE, topology, vmap) or $(NDSLICE, topology, map).
Params:
    methodName = name of the methods to use for opCall and opIndex
    TemplateArgs = template arguments
+/
template aliasCall(string methodName, TemplateArgs...)
{
    /++
    Params:
        value = the value to wrap
    Returns:
        wrapped value with implemented opCall and opIndex methods
    +/
    AliasCall!(T, methodName, TemplateArgs) aliasCall(T)(T value) @property
    {
        return typeof(return)(value);
    }

    /// ditto
    ref AliasCall!(T, methodName, TemplateArgs) aliasCall(T)(return ref T value) @property @trusted
    {
        return  *cast(typeof(return)*) &value;
    }
}

///
@safe pure nothrow version(mir_core_test) unittest
{
    static struct S
    {
        auto lightConst()() const @property { return S(); }

        auto fun(size_t ct_param = 1)(size_t rt_param) const
        {
            return rt_param + ct_param;
        }
    }

    S s;

    auto sfun = aliasCall!"fun"(s);
    assert(sfun(3) == 4);

    auto sfun10 = aliasCall!("fun", 10)(s);   // uses fun!10
    assert(sfun10(3) == 13);
}

/++
+/
template recurseTemplatePipe(alias Template, size_t N, Args...)
{
    static if (N == 0)
        alias recurseTemplatePipe = Args;
    else
    {
        alias recurseTemplatePipe = Template!(.recurseTemplatePipe!(Template, N - 1, Args));
    }
}

///
@safe version(mir_core_test) unittest
{
    // import mir.ndslice.topology: map;
    alias map(alias fun) = a => a; // some template
    static assert (__traits(isSame, recurseTemplatePipe!(map, 2, "a * 2"), map!(map!"a * 2")));
}

/++
+/
template selfAndRecurseTemplatePipe(alias Template, size_t N, Args...)
{
    static if (N == 0)
        alias selfAndRecurseTemplatePipe = Args;
    else
    {
        alias selfAndRecurseTemplatePipe = Template!(.selfAndRecurseTemplatePipe!(Template, N - 1, Args));
    }
}

///
@safe version(mir_core_test) unittest
{
    // import mir.ndslice.topology: map;
    alias map(alias fun) = a => a; // some template
    static assert (__traits(isSame, selfAndRecurseTemplatePipe!(map, 2, "a * 2"), map!(pipe!("a * 2", map!"a * 2"))));
}

/++
+/
template selfTemplatePipe(alias Template, size_t N, Args...)
{
    static if (N == 0)
        alias selfTemplatePipe = Args;
    else
    {
        alias selfTemplatePipe = Template!(.selfTemplatePipe!(Template, N - 1, Args));
    }
}

///
@safe version(mir_core_test) unittest
{
    // import mir.ndslice.topology: map;
    alias map(alias fun) = a => a; // some template
    static assert (__traits(isSame, selfTemplatePipe!(map, 2, "a * 2"), map!(pipe!("a * 2", map!"a * 2"))));
}