Advertisement
Guest User

Untitled

a guest
Aug 30th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. function just(x) {
  2. return {
  3. empty : false,
  4. map : (f) => just(f(x)), // := Functor
  5. flatMap : (f) => f(x), // := Monad
  6. ap : (a) => a.map(x), // := Applicative Functor
  7. show : () => 'just(' + x + ')'
  8. };
  9. }
  10.  
  11. function none() {
  12. return {
  13. empty : true,
  14. map : (f) => none(), // := Functor
  15. flatMap : (f) => none(), // := Monad
  16. ap : (a) => none(), // := Applicative Functor
  17. show : () => 'none()'
  18. };
  19. }
  20.  
  21. const log = x => console.log( x.show() )
  22.  
  23. const fn_curry_add = x => y => x + y;
  24. const fn_increment = fn_curry_add(1);
  25. const five = just(5);
  26.  
  27. //Using map from Funtor :
  28. const inc_five = five.map(fn_increment);
  29. log(inc_five) // just(6)
  30. const inc_inc_five = inc_five.map(fn_increment);
  31. log(inc_inc_five) // just(7)
  32.  
  33. //Using ap from Applicative Functor :
  34. const add = just(fn_curry_add);
  35. const three = just(3);
  36. const result_of_add = add.ap(five).ap(three);
  37. log(result_of_add) //just(8)
  38.  
  39. //Using flatMap from Monad :
  40. const half = x => x%2===0 ? just(x/2) : none()
  41. const eighty = just(80);
  42. const chained = eighty.flatMap(half).flatMap(half).flatMap(half).flatMap(half);
  43. log(chained) //just(5)
  44. log(chained.flatMap(half)) //none()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement