Skip to content

Instantly share code, notes, and snippets.

@DrBoolean
Created March 4, 2015 02:33
Show Gist options
  • Save DrBoolean/c0204ed57cf63a70dfe0 to your computer and use it in GitHub Desktop.
Save DrBoolean/c0204ed57cf63a70dfe0 to your computer and use it in GitHub Desktop.
Coyoneda
// 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));
});
@DrBoolean
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment