Skip to content

Instantly share code, notes, and snippets.

@zaetrik
Created May 4, 2020 13:00
Show Gist options
  • Save zaetrik/62e1a1013351cc1db507ef9a268dae94 to your computer and use it in GitHub Desktop.
Save zaetrik/62e1a1013351cc1db507ef9a268dae94 to your computer and use it in GitHub Desktop.
Monoid Type Class Introduction
// Monoid type class
// Used to merge two contexts together
// Mostly taken from https://dev.to/gcanti/getting-started-with-fp-ts-monoid-ja0
// A Monoid extends the Semigroup type class
// "A Monoid is any Semigroup that happens to have a special value which is "neutral" with respect to concat" - https://dev.to/gcanti/getting-started-with-fp-ts-monoid-ja0
// empty does nothing else than returning that special neutral value
interface Monoid<A> extends Semigroup<A> {
readonly empty: A
}
// This how we could implement a Monoid instance for the Semigroup (number, *) for multiplication
const monoidProduct: Monoid<number> = {
concat: (x, y) => x * y,
empty: 1 // => 1 is the neutral value for multiplication, e.g. 1 * 10 = 10
}
// the empty method has to follow two laws/rules => right & left identity
// Right identity => concat(x, empty) = x, for all x in A
// Left identity => concat(empty, x) = x, for all x in A
// The empty value should not change x
// If we look back to our monoidProduct => concat(10, empty) = 10 & concat(empty, 10) = 10
// Implementation of Monoid for the Semigroup (number, +) for addition
const monoidSum: Monoid<number> = {
concat: (x, y) => x + y,
empty: 0 // => concat(10, empty) = 10 & concat(empty, 10) = 10
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment