Doug Beardsley
Takt
Abstract control flow
names = [];
for ( var i = 0; i < people.length; i++ ) {
names[i] = people[i].name;
}
names = people.map(function(p) { return p.name; });
or (ECMAScript 6)
names = people.map(p => p.name);
minors = [];
for ( var i = 0; i < people.length; i++ ) {
if ( people[i].age < 18 ) {
minors.push(people[i]);
}
}
names = people.filter(p => p.age < 18);
var sum = 0;
for ( var i = 0; i < values.length; i++ ) {
sum += values[i];
}
sum = values.reduce((a, b) => a + b, 0);
for ( i = 0; i < p; i++ ) {
if ( someFunc(arr[i]) > threshold ) {
for ( j = 0; j < q; j++ ) {
if ( anotherCondition(foo[i][j]) ) {
// stuff here
}
}
}
}
function foo(x, y, z) {
return 2 * x^2 + 3 * y - 5 * z;
} // Call with: foo(x, y, z);
could be written like
function foo(x) {
return ((y, z) => 2 * x^2 + 3 * y - 5 * z);
} // Call with: foo(x)(y, z);
or
function foo(x) {
return (y => (z => 2 * x^2 + 3 * y - 5 * z));
} // Call with: foo(x)(y)(z);
foo(x, y, z)
turns into
foo(x)(y)(z)
foo x y z = 2 * x^2 + 3 * y - 5 * z
call with
foo 2 3 4
or
foo 2 3
or
foo 2
Instead of this
values.map(x => plus(1,x));
we can do this
map (plus 1) values
foo x = x + 5
(+) :: Num a => a -> a -> a
foo :: Num a => a -> a
If we know that 5 is an Int
foo :: Int -> Int
NOTE: Lower case a means it's a type variable that can be any type.
def addBigInteger(a:BigInteger, b:BigInteger) : IO[BigInteger]
vs
def addBigInteger(a:BigInteger, b:BigInteger) : BigInteger
or
addBigInteger :: BigInteger -> BigInteger -> IO BigInteger
vs
addBigInteger :: BigInteger -> BigInteger -> BigInteger
def writeFile(path:String, bytes:Array[Byte]) : FileIO[Unit]
def readFile(path:String) : FileIO[Array[Byte]]
writeFile :: FilePath -> Bytes -> FileIO ()
readFile :: FilePath -> FileIO Bytes
doug@takt.com
http://github.com/mightybyte/three-essentials