Skip to content

Instantly share code, notes, and snippets.

@zaetrik
Created May 4, 2020 13:21
Show Gist options
  • Save zaetrik/6a0ddad65358ff8b5e7d9ab7e32881af to your computer and use it in GitHub Desktop.
Save zaetrik/6a0ddad65358ff8b5e7d9ab7e32881af to your computer and use it in GitHub Desktop.
Monoid Type Class Option
// When we can find a Monoid instance for A we can create one for Option<A>
// When we take a look at the fp-ts implementation it will become clearer
export function getApplySemigroup<A>(S: Semigroup<A>): Semigroup<Option<A>> {
return {
concat: (x, y) => (isSome(x) && isSome(y) ? some(S.concat(x.value, y.value)) : none)
}
}
export function getApplyMonoid<A>(M: Monoid<A>): Monoid<Option<A>> {
return {
...getApplySemigroup(M),
empty: some(M.empty)
}
}
// We see that getApplyMonoid uses getApplySemigroup and just extends it with empty
// which just returns the empty value of the Monoid A wrapped in an Option, so we get Option<A>
// So if A has a empty value and can thus become an instance of the Monoid type class, we can also derive a Monoid instance for Option<A>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment