category_theory/monoid

The Monoid module contains the Monoid type with who’s minimal implementations are mempty and mappend.
We also define the mconcat function in terms of mempty and mappend.
Finally, this module contains several instances for the monoid type.

Types

A monoid is a set with a binary operation or a a single object category with a set of morphisms that follow the rules of composition.

class Monoid m where
  mempty  :: m
  mappend :: m -> m -> m

Laws:

  • mappend mempty x = x
  • mappend x mempty = x
  • mappend x (mappend y z) = mappend (mappend x y) z
  • mconcat = foldr mappend mempty

Examples

let int_sum_monoid = Monoid(mempty: 0, mappend: fn(x: Int, y: Int) { x + y })
int_sum_monoid
|> mconcat([2, 3, int_sum_monoid.mempty, 4])
|> int_sum_monoid.mappend(10)
// -> 19
let bool_and_monoid = Monoid(mempty: True, mappend: bool.and)
True
|> bool_and_monoid.mappend(False)
|> bool_and_monoid.mappend(bool_and_monoid.mempty)
// -> False
pub type Monoid(m) {
  Monoid(mempty: m, mappend: fn(m, m) -> m)
}

Constructors

  • Monoid(mempty: m, mappend: fn(m, m) -> m)

Functions

pub fn function_monoid(mono_b: Monoid(a)) -> Monoid(fn(b) -> a)

Monoid instance for functions where the result type must be a Monoid instance.

pub fn list_monoid() -> Monoid(List(a))

Returns the canonical implementation of the monoid type for List.

Examples

[1, 2]
|> mono_list.mappend([3, 4, 5])
|> mono_list.mappend(mono_list.mempty)
|> mono_list.mappend([6])
// -> [1, 2, 3, 4, 5, 6]
pub fn mconcat(mono: Monoid(a), monoid_list: List(a)) -> a

Fold a list of monoids using mappend.

pub fn option_monoid(mono_a: Monoid(a)) -> Monoid(Option(a))

Returns the canonical implementation of the monoid type for Option(a).
We must have a Monoid(a) type instance.

Examples

let mono_string = Monoid(mempty: "", mappend: fn(x: String, y: String) -> String { x <> y })
let mono_maybe = option_monoid(mono_string)

Some("ab")
|> mono_maybe.mappend(Some("cd"))
// -> Some("abcd")
mono_maybe.mappend(Some("abc"), maybe.mempty)
// -> None
pub fn triple_monoid(
  mono_a: Monoid(a),
  mono_b: Monoid(b),
  mono_c: Monoid(c),
) -> Monoid(#(a, b, c))

Returns the canonical implementation of the monoid type for Triple.
We must have a Monoid type instance for a, b, and c.

pub fn tuple_monoid(
  mono_a: Monoid(a),
  mono_b: Monoid(b),
) -> Monoid(#(a, b))

Returns the canonical implementation of the monoid type for Tuple.
We must have a Monoid(a) and a Monoid(b) type instance.

pub fn unit_monoid() -> Monoid(Nil)

Returns the canonical implementation of the monoid type for Nil (unit type).

Examples

mono_unit.mappend(mono_unit.mempty, Nil)
// -> Nil
Search Document