Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- operator (>>=) 1 left { $a, $b } => #{ $a.bind($b) }
- operator (>>) 1 left { $a, $b } => #{ $a.bind((_) => $b) }
- function doM(gen) {
- function step(value) {
- var result = gen.next(value);
- if (result.done) {
- return result.value
- }
- return result.value.bind(step)
- }
- return step()
- }
- macro (<-) {
- rule infix { $a:ident | $e:expr } => { const $a = yield $e }
- }
- macro do {
- rule { {$expr ...} } => {
- doM(function*() {
- $expr ...
- }())
- }
- }
- function Just(value) {
- this.value = value;
- }
- Just.prototype.bind = function(fn) {
- return fn(this.value)
- }
- Just.prototype.toString = function() {
- return "Just(" + this.value + ")"
- }
- function Nothing(value) {}
- Nothing.prototype.bind = function(_) {
- return this
- }
- Nothing.prototype.toString = function() {
- return "Nothing()"
- }
- function sqrtMaybe(x) {
- return x >= 0 ? new Just(Math.sqrt(x)) : new Nothing()
- }
- const result = do {
- x <- sqrtMaybe(25)
- y <- sqrtMaybe(36)
- return new Just(x + y)
- }
- alert(result) // Just(11)
Advertisement
Add Comment
Please, Sign In to add comment