Dart Functional Programming
void main() {
var test = compose([add(1), subtract(10)]);
print(test(2));// 10-2+1=9
}
add(int x) {
return (int y) => x + y;
}
subtract(int x) {
return (int y) => x - y;
}
class Compose {
Function first;
List<Function> funcs;
Compose(List<Function> funcs) {
var reversedFuncs = funcs.reversed.toList();
this.first = reversedFuncs.first;
this.funcs = reversedFuncs.sublist(1);
}
call(List<Function> args) {
var ret = this.first(args);
for(var f in this.funcs) {
ret = f(ret);
}
return ret;
}
}
compose(List<Function> funcs) {
if(funcs == null) {
return (x) => x;
}
if(funcs.length == 1) {
return funcs[0];
} else {
return new Compose(funcs);
}
}