Skip to content

Instantly share code, notes, and snippets.

@dg3feiko
Created November 3, 2016 04:46
Show Gist options
  • Save dg3feiko/37fdbac90f9554df2cb80079ce34351c to your computer and use it in GitHub Desktop.
Save dg3feiko/37fdbac90f9554df2cb80079ce34351c to your computer and use it in GitHub Desktop.
'use strict';
//data type
class Option { }
Option.None = class { toString() { return "None" } };
Option.Some = class { constructor(value) { this.some = value } toString() { return `Some:${this.some}` } };
//computation builder
let maybe = function (genFunc) {
let gen = new genFunc();
let ret;
while (true) {
let yieldable = gen.next(ret);
//"Return"
if (yieldable.done) {
return new Option.Some(yieldable.value);
}
//"Bind"
if (yieldable.value instanceof Option.Some) {
ret = yieldable.value.some;
} else if (yieldable.value instanceof Option.None) {
return yieldable.value;
} else {
throw new Error("Invalid value.");
}
}
}
//function work with the data type
let divide = function (top, bottom) {
if (bottom === 0) {
return new Option.None();
} else {
return new Option.Some(top / bottom);
}
}
//usage
let res1 = maybe(function* () {
let a = yield divide(24, 2);
let b = yield divide(a, 0)
let c = yield divide(b, 4)
return c;
})
console.log("Result1:", res1.toString());
//output: Result: None
let res2 = maybe(function* () {
let a = yield divide(24, 2);
let b = yield divide(a, 3)
let c = yield divide(b, 4)
return c;
})
console.log("Result2:", res2.toString());
//output Result: Some:1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment