Created
July 16, 2018 04:45
-
-
Save abiodun0/b2d07a0d8b0a3b09a8bf86b005e07457 to your computer and use it in GitHub Desktop.
Fluture with runkit monad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require("@babel/polyfill") | |
const { implement, Functor } = require("@masaeedu/fp") | |
const Fluture= require("fluture") | |
// We can just get map from of and chain for free everywhere | |
const deriveFunctor = implement(Functor) | |
// Identity monad | |
const id = x => x; | |
const Identity = deriveFunctor({ of: id, chain: id }); | |
const Maybe = (() => { | |
// ADT | |
const Just = x => ({ hasValue: true, x }); | |
const Nothing = { hasValue: false }; | |
const match = ({ Just, Nothing }) => ({ hasValue, x }) => | |
hasValue ? Just(x) : Nothing; | |
// Monad transformer | |
const T = M => { | |
// Monad | |
const of = x => M.of(Just(x)); | |
const chain = f => | |
M.chain(match({ | |
Nothing: M.of(Nothing), | |
Just: f | |
})); | |
// MonadTrans | |
const liftT = M.map(Just); | |
return deriveFunctor({ of, chain, liftT }) | |
}; | |
// Monad | |
const { of, chain } = T(Identity) | |
return deriveFunctor({ Just, Nothing, match, T, of, chain }); | |
})(); | |
const MaybeOfFluture = Maybe.T(Fluture) | |
const tests = [ | |
MaybeOfFluture.map(x => x * 2)(Fluture.of(Maybe.Nothing)), // => Nothing | |
MaybeOfFluture.map(x => x * 2)(Fluture.of(Maybe.Just(21))) // => 42 | |
] | |
tests.map(f => f.fork(console.error, console.log)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment