Skip to content

Instantly share code, notes, and snippets.

@hallettj
Created March 28, 2014 08:03
Show Gist options
  • Save hallettj/9827604 to your computer and use it in GitHub Desktop.
Save hallettj/9827604 to your computer and use it in GitHub Desktop.
Trying to apply ES6 generators to create monad comprehensions. Unfortunately it looks like this will not work with monads that contain multiple values, such as arrays.
/*
* The implementation
*/
function du(comprehension) {
return function(/* args */) {
var gen = comprehension.apply(null, arguments)
return next();
function next(v) {
var res = gen.next(v)
return (!res.done && res.value) ? flatMap(res.value, tryNext) : res.value
}
function tryNext(v) {
try {
return next(v)
}
catch (err) {
return gen.throw(err)
}
}
}
}
function flatMap(m, f) {
if (typeof m.then === 'function') {
return m.then(f)
}
else if (typeof m.map === 'function' && typeof m.length === 'number') {
return flatten(m.map(f))
}
else {
throw new TypeError("No implementation for this argument!")
}
}
function flatten(xs) {
if (!xs || !xs.reduce) {
return xs
}
return xs.reduce(function(flat, x) {
return flat.concat(x)
}, [])
}
/*
* An array monad in action
*/
var guests = [
{ name: "Sophia", vegetarian: true, peanutAllergy: false },
{ name: "Madison", vegetarion: false, peanutAllergy: false },
{ name: "Liam", vegetarion: true, peanutAllergy: true },
{ name: "Noah", vegetarian: true, peanutAllergy: false },
{ name: "Elizabeth", vegetarian: false, peanutAllergy: true }
]
var entrees = [
{ name: "Meatballs", vegetarian: false, peanut: false },
{ name: "Pad Thai", vegetarion: true, peanut: true },
{ name: "BLT", vegetarion: false, peanut: false },
{ name: "Caesar Salad", vegetarian: true, peanut: false },
{ name: "Game Hen", vegetarian: false, peanut: true }
]
var acceptablePairings = du(function*() {
var guest = yield guests
var entree = yield entrees
if (guest.peanutAllergy && entree.peanut) {
return []
}
else if (guest.vegetarian && !entree.vegetarian) {
return []
}
else {
return [[guest.name, entree.name]]
}
})();
// Upon calling `gen.next()` with the second entree, an error is reported:
//
// > Error: Generator has already finished
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment