Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Last active January 3, 2016 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robotlolita/8511727 to your computer and use it in GitHub Desktop.
Save robotlolita/8511727 to your computer and use it in GitHub Desktop.
function flatMap(f, xs) {
return xs.reduce(function(ys, x){ return ys.concat(f(x)) }, [])
}
function ap(fs, ys) {
return flatMap(function(f){ return ys.map(f) }, fs)
}
function inverses(a){
return [a, -a]
}
function flatten(xs){
return flatMap(function(a){ return a }, xs)
}
var xs = flatMap(inverses, [1, 2, 3, 4, 5, 6, 7, 8, 9])
var fs = xs.map(function(a){
return function(b) {
return [a + b, a - b] }})
flatten(ap(fs, xs))
// => Array(648): [2, 0, 0, 2, 3, -1, -1, 3, 4, ...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment