I'm trying to understand the relationship between a functor and a monoid. They are often mentioned together but I haven't been able to quite connect the dots.
I understand that, simply speaking, in programming a monoid can be thought of as a structure or data type with an associative append/concat function used to combine elements in the structure as well as an identity element where if you commutatively combine the identity value with an element in your structure it will always return the same element.
I also recognize that in programming a functor can be thought of as a collection-like structure with a map operation similar to Array.prototype.map().
Could anyone help me see the big picture here? Also, please feel free to let me know if I'm missing anything in my understanding of these concepts.
A functor is a structure-preserving transformation between categories.
It
Sort of like homomorphisms between categories.
In FP language like Haskell, the definition of Functor class has two parts:
class Functor f where
fmap :: (a -> b) -> (f a -> f b)
The type f is what maps objects (Haskell types) to other objects in the same category (Haskell types). It maps a to f a.
A monoid (semigroups with identity)
S• : S × S → SS, e : 1 → SDefined in Haskell as following
class Semigroup s => Monoid s where
mempty :: s
mappend :: s -> s -> s
mappend = (<>)
They are two different things but
They are often mentioned together but I haven't been able to quite connect the dots.
they are often mentioned together because of one another thing, a Monad.
A monad (special cases of monoids or monoids among endofunctors) is
T : S → S (An endofunctor is simply a functor from a category to itself)μ : S × S → S, where × means functor composition (join)η : I → S, where I is the identity endofunctor on S (return)which essentially combines those two concepts.
In Haskell
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
implies
fmap f m = m >>= return . f
More succinctly put,
A monad is just a monoid in the category of endofunctors, what's the problem?
which you might have seen jokingly used all over FP forums. It's a version of
a monad in X is just a monoid in the category of endofunctors of X
originally from Mac Lane's Categories for the Working Mathematician.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With