Created
March 4, 2015 02:33
-
-
Save DrBoolean/c0204ed57cf63a70dfe0 to your computer and use it in GitHub Desktop.
Coyoneda
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
// helpers | |
var compose = function(f,g) { | |
return function(x) { | |
return f(g(x)) | |
} | |
} | |
var id = function(x) { return x } | |
// Define Coyoneda | |
var _Coyoneda = function(f, fa) { | |
this.f = f; | |
this.val = fa; | |
} | |
_Coyoneda.prototype.map = function(f) { | |
return Coyoneda(compose(f, this.f), this.val) | |
} | |
_Coyoneda.prototype.lower = function() { return this.val.map(this.f); } | |
var Coyoneda = function(f, fa){ return new _Coyoneda(f, fa); } | |
Coyoneda.lift = function(x){ return Coyoneda(id, x); } | |
// Demo | |
var arr = [1,2,3] | |
var coyo_arr = Coyoneda.lift(arr); | |
var coyo_result = coyo_arr.map(function(x) { return x + 1 }).map(function(x) { return String(x) + '!' }) | |
console.log("RESULT", coyo_result.lower()); | |
//no map needed w/o lower() | |
coyo_result.val.forEach(function(x){ | |
console.log(coyo_result.f(x)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Coyoneda holds two values: a function that will build as we map and a functor-like container type.
The demo suggests we loop fuse the two maps and only iterate once.
A second forEach is thrown in to show that we don't need map after all, which is why
Set
can be "mapped" in yoneda, then run later by picking it apart.