Skip to content

Instantly share code, notes, and snippets.

@zaetrik
Last active May 12, 2020 08:38
Show Gist options
  • Save zaetrik/a8ba458639faae4ddee7701841b387b1 to your computer and use it in GitHub Desktop.
Save zaetrik/a8ba458639faae4ddee7701841b387b1 to your computer and use it in GitHub Desktop.
Monads: flatMap & chain
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