init::foldable

init/src/foldable.mo

instance_#
pub instance {A : Type} Semigroup (List A) {
    def combine (a b : List A) : List A := List.append a b
}
instance_#
pub instance {A : Type} Monoid (List A) {
    def mempty (u : Unit) : List A := List.empty
}
instance_#
pub instance Semigroup String {
    def combine (a b : String) : String := String.concat a b
}
instance_#
pub instance Monoid String {
    def mempty (u : Unit) : String := ""
}
instance_#
pub instance Foldable List {
    def foldr (f : A -> B -> B) (z : B) (t : List A) : B :=
        match t {
            empty => z,
            cons a tail => (f a (Foldable.foldr f z tail) : B)
        }

    def foldl (f : B -> A -> B) (z : B) (t : List A) : B :=
        match t {
            empty => z,
            cons a tail => (Foldable.foldl f (f z a) tail : B)
        }
}
instance_#
pub instance Foldable Option {
    def foldr (f : A -> B -> B) (z : B) (t : Option A) : B :=
        match t {
            none => z,
            some a => f a z
        }

    def foldl (f : B -> A -> B) (z : B) (t : Option A) : B :=
        match t {
            none => z,
            some a => f z a
        }
}