Skip to content

Instantly share code, notes, and snippets.

@danclien
Last active December 30, 2015 02:09
Show Gist options
  • Save danclien/7760523 to your computer and use it in GitHub Desktop.
Save danclien/7760523 to your computer and use it in GitHub Desktop.
Option/Maybe monad in JavaScript
function bind(/* (M a) */ monadicValue, /* (a -> M b) */ operation ) {
//Step 1: Unwrap `monadicValue` so type `(M a)` so it's of type `a`
//Step 2: Shoves the `a` through the `operation`
//How it shoves a through the operation depends on what you want it to do
//Step 3: Returns a monadic value of type `(M b)`
}
/* Maybe/Option monad
* If the value is None/Nothing, stop and return None/Nothing,
* else, call `operation`
*/
Array.prototype.bind = function(operation) {
if(this.length == 0) {
return [];
} else {
return operation(this[0]);
}
}
/*` unit` for an Array is just wrapping a value in []'s */
var a = [42]; //represents a wrapped 42, Scala: Some(42), Haskell: Just 42
var b = []; //represents "null", Scala: None, Haskell: Nothing
/* `Array#forEach` is like `bind`
* where `bind` allows you to do an operation if monadicValue isn't "null"
*
* `a` is `monadicValue` of type (M a)
* `operation` is the anonymous function
* Parameter in unwrapped value of type (a)
* Returns a wrapped value of type (M b) (in case this type (a) === type (b))
**/
a.bind(function(value) {
/* Do something with the value in `a` */
console.log(value);
return [value];
});
/*
* `b` is `monadicValue`
* `operation` is the anonymous function
*/
b.bind(function(value) {
/* Since `b` represents nothing, this never runs */
console.log(value);
return [value];
});
var c = [100]; //represents a wrapped 100, Scala: Some(100), Haskell: Just 100
/* To do something when `a` and `c` are not None/Nothing */
var result1 = a.bind(function(valueA) {
return c.bind(function(valueC) {
console.log(valueA + valueC);
return [valueA + valueC];
});
});
/* To do something when `a`, `b`, and `c` are not None/Nothing */
var result2 = a.bind(function(valueA) {
return b.bind(function(valueB) {
return c.bind(function(valueC) {
console.log(valueA + valueB + valueC);
return [valueA + valueB + valueC];
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment