Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active October 29, 2015 13:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save branneman/2ac80a17b9f90d9919ce to your computer and use it in GitHub Desktop.
Save branneman/2ac80a17b9f90d9919ce to your computer and use it in GitHub Desktop.
Functional Composition through functor map
// add :: Number -> Number -> Number
var add = function(left) { return function(right) { return left + right } };
// multiply :: Number -> Number -> Number
var multiply = function(left) { return function(right) { return left * right } };
// map :: (a -> b) -> Functor a -> Functor b
var map = function(fn, val) { return val.map(fn) };
//
// Functor: Identity
//
var Identity = function(val) {
this.val = val;
};
Identity.of = function(x) {
return new Identity(x);
};
Identity.prototype.map = function(fn) {
return Identity.of(fn(this.val));
};
//
// Functor: Function
//
Function.prototype.map = function(fn2) {
return function(val) {
return fn2(this(val));
}.bind(this);
};
//
// Function composition through functor map
//
var formula = map(multiply(2), add(1)); //=> (Number -> Number)
var result = map(formula, Identity.of(3)); //=> Identity(8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment