Skip to content

Instantly share code, notes, and snippets.

@dwickstrom
Last active May 6, 2018 19:29
Show Gist options
  • Save dwickstrom/5e3e2e3e1320f1668e88b3bac7b6f039 to your computer and use it in GitHub Desktop.
Save dwickstrom/5e3e2e3e1320f1668e88b3bac7b6f039 to your computer and use it in GitHub Desktop.
List monad in JS
const identity = x => x
// Monoid
Array.empty = () => []
Array.prototype.empty = Array.empty
// Monad
Array.prototype.chain = function (f) {
return Function.prototype.apply.bind([].concat, []) (this.map(f))
}
// Applicative
Array.prototype.ap = function (other) {
return this.chain(f => other.map(x => f(x)))
}
// Traversable
Array.prototype.traverse = function(of, f) {
return this.reduce((ys, x) =>
ys.map(x => y => x.concat([y])).ap(f(x)), of(this.empty))
}
Array.prototype.sequence = function(of) {
return this.traverse(of, identity)
}
Array.prototype.foldMap = function(f, empty) {
return empty != null
? this.reduce((acc, x, i) => acc.concat(f(x, i)), empty)
: this.map(f).reduce((acc, x) => acc.concat(x))
}
Array.prototype.fold = function(empty) {
return this.foldMap(identity, empty)
}
Array.of(1).map(double) // [[1, 1]]
Array.of(1).chain(double) // [1, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment