Last active
May 12, 2020 08:38
-
-
Save zaetrik/a8ba458639faae4ddee7701841b387b1 to your computer and use it in GitHub Desktop.
Monads: flatMap & chain
This file contains 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
interface Monad<M> extends Applicative<M> { | |
flatMap: <A, B>(f: (a: A) => M<B>) => ((ma: M<A>) => M<B>); | |
} | |
// An implementation could look like this | |
const OptionMonad = { | |
...OptionApplicative, | |
flatMap: (f) => (ma) => (isNone(ma) ? none : f(ma.value)), | |
} | |
// In fp-ts a variant of flatMap is used => chain | |
// chain is almsot like flatMap but the arguments are rearranged | |
interface Monad<M> extends Applicative<M> { | |
chain: <A, B>(ma: M<A>, f: (a: A) => M<B>) => M<B>; | |
} | |
// An implementation with chain could look like this | |
const OptionMonad = { | |
...OptionApplicative, | |
chain: (ma, f) => (isNone(ma) ? none : f(ma.value)), | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment