Created
May 4, 2014 11:56
-
-
Save chrisvest/913ed811a8cbd283c04f to your computer and use it in GitHub Desktop.
This file contains 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
var Functor = ['map']; | |
var Applicative = ['maps', 'wrap'].concat(Functor); | |
var Monad = ['mapcat'].concat(Applicative); | |
var compliment = function (f) { | |
return function (x) { | |
return !f(x); | |
} | |
} | |
Object.prototype.check = function (iface) { | |
var candidate = this; | |
var isDefined = function(f) { return candidate[f]; }; | |
if (!iface.every(isDefined)) { | |
var type = candidate.constructor.name; | |
var absent = iface.filter(compliment(isDefined)); | |
var msg = type + " does not implement " + absent; | |
throw new Error(msg); | |
} | |
} | |
Object.prototype.implement = function (iface, instance) { | |
instance.check(iface); | |
for (var i = 0; i < iface.length; i++) { | |
var fname = iface[i]; | |
this.prototype[fname] = instance[fname]; | |
} | |
} | |
Array.implement(Monad, { | |
map: Array.prototype.map, | |
wrap: function (x) { | |
return [x]; | |
}, | |
maps: function(Fa2b) { | |
return this.map(function (x, i) { | |
return Fa2b[i](x); | |
}); | |
}, | |
mapcat: function(a2b) { | |
return this.reduce(function (res, xs) { | |
return res.concat(xs.map(a2b)); | |
}, []); | |
} | |
}); | |
var xs = [[1,2,3],[4,5,6]]; | |
console.log(xs); | |
var ys = xs.mapcat(function (x) { return "a" + x; }); | |
console.log(ys); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment