Last active
October 29, 2015 13:11
-
-
Save branneman/2ac80a17b9f90d9919ce to your computer and use it in GitHub Desktop.
Functional Composition through functor map
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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