Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.