Guest User

Untitled

a guest
Jul 15th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. require("@babel/polyfill")
  2. const { implement, Functor } = require("@masaeedu/fp")
  3.  
  4. const Fluture= require("fluture")
  5.  
  6. // We can just get map from of and chain for free everywhere
  7. const deriveFunctor = implement(Functor)
  8.  
  9. // Identity monad
  10. const id = x => x;
  11. const Identity = deriveFunctor({ of: id, chain: id });
  12.  
  13. const Maybe = (() => {
  14. // ADT
  15. const Just = x => ({ hasValue: true, x });
  16. const Nothing = { hasValue: false };
  17. const match = ({ Just, Nothing }) => ({ hasValue, x }) =>
  18. hasValue ? Just(x) : Nothing;
  19.  
  20. // Monad transformer
  21. const T = M => {
  22. // Monad
  23. const of = x => M.of(Just(x));
  24. const chain = f =>
  25. M.chain(match({
  26. Nothing: M.of(Nothing),
  27. Just: f
  28. }));
  29.  
  30. // MonadTrans
  31. const liftT = M.map(Just);
  32.  
  33. return deriveFunctor({ of, chain, liftT })
  34. };
  35.  
  36. // Monad
  37. const { of, chain } = T(Identity)
  38.  
  39. return deriveFunctor({ Just, Nothing, match, T, of, chain });
  40. })();
  41.  
  42. const MaybeOfFluture = Maybe.T(Fluture)
  43. const tests = [
  44. MaybeOfFluture.map(x => x * 2)(Fluture.of(Maybe.Nothing)), // => Nothing
  45. MaybeOfFluture.map(x => x * 2)(Fluture.of(Maybe.Just(21))) // => 42
  46. ]
  47.  
  48. tests.map(f => f.fork(console.error, console.log))
Add Comment
Please, Sign In to add comment