1 module fptools.fp; 2 3 template FP(T) { 4 import fptools.native : take, takeWhile, map, drop, dropWhile, filter, zipWith; 5 6 alias Condition = bool delegate(T); 7 alias Func = T delegate(T); 8 alias DFunc = T delegate(T, T); 9 alias TFunc = T[] delegate(T[]); 10 alias TCond = bool delegate(T[]); 11 12 /++ 13 Functional Programming Pipe 14 +/ 15 struct Pipe { 16 import fptools.native : reduce, all, any; 17 18 T[] list; 19 20 /++ 21 Input constructor 22 +/ 23 this(T[] input) { 24 this.list = input; 25 } 26 27 /++ 28 Same as constructor 29 +/ 30 void input(T[] array) { 31 this.list = array; 32 } 33 34 /++ 35 Output with copy 36 +/ 37 T[] output() { 38 return this.list[]; 39 } 40 41 /++ 42 Process 43 +/ 44 void proc(TFunc[] funcs...) { 45 foreach(f; funcs) { 46 this.list = f(this.list); 47 } 48 } 49 50 /++ 51 reduce 52 +/ 53 T reduce(DFunc op) { 54 return reduce(op, this.list); 55 } 56 57 /++ 58 all 59 +/ 60 bool all(Condition p) { 61 return all(p, this.list); 62 } 63 64 /++ 65 any 66 +/ 67 bool any(Condition p) { 68 return any(p, this.list); 69 } 70 } 71 72 /++ 73 seq (Like R) 74 +/ 75 T[] seq (T start, T end, T step = 1) { 76 T diff = (end - start) / step; 77 ulong l = cast(ulong)diff + 1; 78 T[] result; 79 result.length = l; 80 foreach(i; 0 .. l) { 81 result[i] = start + step * cast(T)i; 82 } 83 return result; 84 } 85 86 /++ 87 take 88 +/ 89 TFunc take(int n) { 90 return (T[] xs) => take(n, xs); 91 } 92 93 /++ 94 takeWhile 95 +/ 96 TFunc takeWhile(Condition p) { 97 return (T[] xs) => takeWhile(p, xs); 98 } 99 100 /++ 101 map 102 +/ 103 TFunc map(Func f) { 104 return (T[] xs) => map(f, xs); 105 } 106 107 /++ 108 drop 109 +/ 110 TFunc drop(int n) { 111 return (T[] xs) => drop(n, xs); 112 } 113 114 /++ 115 dropWhile 116 +/ 117 TFunc dropWhile(Condition p) { 118 return (T[] xs) => dropWhile(p, xs); 119 } 120 121 /++ 122 filter 123 +/ 124 TFunc filter(Condition p) { 125 return (T[] xs) => filter(p, xs); 126 } 127 128 /++ 129 zipWith 130 +/ 131 TFunc zipWith(DFunc op, T[] other) { 132 return (T[] xs) => zipWith(op, xs, other); 133 } 134 }