Advertisement
Guest User

Monadic sugar in JavaScript using sweet.js macros

a guest
Nov 28th, 2015
103
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 Just(value) {
  5.     this.value = value;
  6. }
  7.  
  8. Just.prototype.bind = function(fn) {
  9.     return fn(this.value)
  10. }
  11.  
  12. Just.prototype.toString = function() {
  13.     return "Just(" + this.value + ")"
  14. }
  15.  
  16. function Nothing(value) {}
  17.  
  18. Nothing.prototype.bind = function(_) {
  19.     return this
  20. }
  21.  
  22. Nothing.prototype.toString = function() {
  23.     return "Nothing()"
  24. }
  25.  
  26. function sqrtMaybe(x) {
  27.     return x >= 0 ? new Just(Math.sqrt(x)) : new Nothing()
  28. }
  29.  
  30. const result = sqrtMaybe(25)
  31.     >>= (x) => sqrtMaybe(36)
  32.     >>= (y) => new Just(x + y)
  33.    
  34. alert(result)   // => Just(11)
  35.  
  36. const result2 = sqrtMaybe(-1)
  37.     >>= (x) => alert("This code won't be executed")
  38.  
  39. alert(result2)  // => Nothing()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement