Created
January 4, 2015 19:41
-
-
Save simonh1000/b91538bd863a38855444 to your computer and use it in GitHub Desktop.
Maybe Monad in Javascript
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
"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