Skip to content

Instantly share code, notes, and snippets.

@simonh1000
Created January 4, 2015 19:41
Show Gist options
  • Save simonh1000/b91538bd863a38855444 to your computer and use it in GitHub Desktop.
Save simonh1000/b91538bd863a38855444 to your computer and use it in GitHub Desktop.
Maybe Monad in Javascript
"use strict"
/*
An implementation of the Maybe monad in ES6, representing
- Maybe as a singleton array
- Nothing and null
Compiled and run with Traceur
traceur --out build.js --script maybe.js
*/
var $traceurRuntime = require('traceur-runtime');
class Maybe {
constructor() {
this.value = [];
}
nothing() {
this.value = [];
return this;
}
unit(x) {
this.value = [x];
return this;
}
bind(f) {
switch (this.value.length) {
case 0: return this; // returns the monad with value = []
case 1: return f(this.value[0]);
}
}
get() {
switch (this.value.length) {
case 0: return null;
case 1: return this.value[0];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment