Guest User

Do-notation in JavaScript

a guest
Nov 28th, 2015
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. operator (>>=) 1 left { $a, $b } => #{ $a.bind($b) }
  2. operator (>>) 1 left { $a, $b } => #{ $a.bind((_) => $b) }
  3.  
  4. function doM(gen) {
  5.     function step(value) {
  6.         var result = gen.next(value);
  7.         if (result.done) {
  8.             return result.value
  9.         }
  10.         return result.value.bind(step)
  11.     }
  12.     return step()
  13. }
  14.  
  15. macro (<-) {
  16.     rule infix { $a:ident | $e:expr } => { const $a = yield $e }
  17. }
  18.  
  19. macro do {
  20.     rule { {$expr ...} } => {
  21.         doM(function*() {
  22.             $expr ...
  23.         }())
  24.     }
  25. }
  26.  
  27. function Just(value) {
  28.     this.value = value;
  29. }
  30.  
  31. Just.prototype.bind = function(fn) {
  32.     return fn(this.value)
  33. }
  34.  
  35. Just.prototype.toString = function() {
  36.     return "Just(" + this.value + ")"
  37. }
  38.  
  39. function Nothing(value) {}
  40.  
  41. Nothing.prototype.bind = function(_) {
  42.     return this
  43. }
  44.  
  45. Nothing.prototype.toString = function() {
  46.     return "Nothing()"
  47. }
  48.  
  49. function sqrtMaybe(x) {
  50.     return x >= 0 ? new Just(Math.sqrt(x)) : new Nothing()
  51. }
  52.  
  53. const result = do {
  54.     x <- sqrtMaybe(25)
  55.     y <- sqrtMaybe(36)
  56.     return new Just(x + y)
  57. }
  58.  
  59. alert(result)   // Just(11)
Advertisement
Add Comment
Please, Sign In to add comment