Monoid

In computer science, a Monoid is a set, a binary operation, and an element of the set with the following rules:

  • Associativity of binary operations
  • The element is the identity

Simply put, a structure is Monoid if the structure is a Semigroup with an element that is the identity. So let's define a new protocol that extends our Semigroup protocol:

protocol Monoid: Semigroup {
    static func identity() -> Self
}

extension Int: Monoid {
    static func identity() -> Int {
        return 0
    }
}

extension String: Monoid {
    static func identity() -> String {
        return ""
    }
}

extension Array: Monoid {
    static func identity() -> Array {
        return []
    }
}

We can test our structure as follows:

numberA <> Int.identity() // 3
"A" <> String.identity() // A

As Monoid has an element, we can use this as an initial and simplify our reduce method as follows:

func mconcat <M: Monoid> (_ elements: [M]) -> M {
    return elements.reduce(M.identity(), combine: <>)
}

Let's test this:

print(mconcat([1, 2, 3])) // 6
print(mconcat(["A", "B", "C"])) // ABC
print(mconcat([[1, 2], [3, 4, 5]])) // [1, 2, 3, 4, 5]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset