think about results, not steps
- First-Class Functions
- Functions can appear anywhere language primitives can appear.
-
First-class functions
- like any other value, they can be passed around
-
Functors
- a collection of X that can apply a function f: X -> Y over itself to create a collection of Y.
// f is a function that takes a single argument and returns a value
// list is a collection of values to map over
// @return a collection of values
function map(f, list) {
var newList = [], length = list.length, i;
for (i = 0; i < length; i++) {
newList.push(f(list[i]));
}
return newList;
}
- Catamorphism
- Higher order functions
- functions can take other functions as arguments
- functions can create other functions
// this is a the Higher Order Function
// takes a function, f, that takes one argument and returns one value
// @return a function that takes two arguments
function mapReducer(f) {
return function(a, b) {
return a.concat(f(b));
}
}
function caps(s) { return s.toUpperCase(); }
function reduce(f, list, initial) {
var result = initial;
for (var i = 0; i < list.length; i++) {
result = f(result, list[i]);
}
return result;
}
reduce(mapReducer(caps), ['orange', 'red', 'blue'], []);
// ['ORANGE', 'RED', 'BLUE']
- Combinators
- A combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments. Wikipedia
- Composition
- combining functions to make new functions
function caps(s) { return s.toUpperCase(); }
function hello(s) { return "Hello " + s; }
// shoutHello demonstrates composition
function shoutHello(f, g) {
return function(value) {
return g(f(value));
}
};
shoutHello(hello, caps)("world"); // HELLO WORLD