Last active
July 15, 2018 06:19
-
-
Save abiodun0/9b1f3170c27e14d6080e5b535a7eb042 to your computer and use it in GitHub Desktop.
Maybe T example
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
const Fluture= require("fluture") | |
// We can just get map from of and chain for free everywhere | |
const deriveFunctor = M => ({ ...M, map: f => M.chain(x => M.of(f(x))) }) | |
// 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, map } = T(Identity) | |
return { Just, Nothing, match, T, of, chain, map }; | |
})(); | |
const FlutureOfMaybe = Maybe.T(Fluture) | |
const tests = [ | |
FlutureOfMaybe.map(x => x * 2)(Fluture.of(Maybe.Nothing)), // => Fluture.of(Nothing) | |
FlutureOfMaybe.map(x => x * 2)(Fluture.of(Maybe.Just(21))) // => Fluture.of(Just(42)) | |
] | |
tests.map(f => f.fork(console.error, console.log)) | |
// The fact that you can do `const { map, of, chain, ...etc } = Maybe.T(Fluture)` | |
// centralizes the complexity of threading maybes through flutures to a single place |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment