-
var multBy2Add3:Function = add(3, mult(2));
-
-
trace(multBy2Add3(10));
-
// 10 * 2 = 20
-
// 20 + 3 = 23
-
-
var add2AndSquare = sq(add(2));
-
-
trace(add2AndSquare(8));
-
// 8 + 2 = 10
-
// 10 * 10 = 100
-
-
var multBy2_3times:Function = repeat(3,mult(2));
-
-
trace(multBy2_3times(3));
-
// 3 * 2 = 6;
-
// 6 * 2 = 12;
-
// 12 * 2 = 24
-
-
// you can also chain for even less readability
-
trace(sq(mult(5,add(1)))(4));
-
// 4 + 1 = 5
-
// 5 * 5 = 25;
-
// 25 * 25 = 625;
-
-
/*
-
outputs:
-
12
-
100
-
24
-
625
-
*/
-
-
// function composition
-
const F:Function = function(a:*):*{return a};
-
function mult(scalar:Number, f:Function=null):Function{
-
if (f == null) f = F;
-
return function(n:Number){
-
return f(n) * scalar;
-
}
-
}
-
-
function add(off:Number, f:Function=null):Function{
-
if (f == null) f = F;
-
return function(n:Number){
-
return f(n) + off;
-
}
-
}
-
function sq(f:Function=null):Function{
-
if (f == null) f = F;
-
return function(n:Number){
-
var v:Number = f(n);
-
return v * v;
-
}
-
}
-
function repeat(times:int, f:Function):Function {
-
if (f == null) f = F;
-
return function (n:Number){
-
var v:Number = n;
-
for (var i:int = 0; i<times; i++) v = f(v);
-
return v;
-
}
-
}
The above shows some interesting function composition... this demo contains the following functions:
mult();
add();
sq();
repeat();
These functions are designed to be combined to create new functions.