Every object must have an identity morphism
↺
↺
↺
Morphisms must compose
"g after f"
Composition must be associative
Category C
Category D
Preserves identity:
Preserves composition:
A functor that maps from some category C
to the same category C
Category C
Pretty much anything with a map method
String
Int
length
"hello"
Option[String]
Option[Int]
Some("hello")
map(length)
5
Some(5)
You can make a category Fun(C, D) of
all the functors between two categories C and D
Can also have a category of endofunctors, Fun(C, C)
(in category theory, pretty much everything turns out to be a category)
Given functors F and G from a category C to a category D,
is a family of morphisms:
for each object x in C
such that
"eta"
trait NatTrans[F[_], G[_]] {
def apply[A](fa: F[A]): G[A]
}
object OptToList extends NatTrans[Option, List] {
def apply[A](fa: Option[A]): List[A] = fa match {
case Some(a) => a :: Nil
case None => Nil
}
}
A functor that takes a pair,
i.e. it maps some product category C x D to some category E
a.k.a tensor category
A category C with an associative bifunctor
"tensor product"
and an object
"identity object"
"unit object"
that is both a left and right identity for
In a monoidal category
with tensor product
and identity object
a monoid consists of:
"myu"
"multiplication"
"eta"
"unit"
trait Monoid[A] {
def unit: A
def multiply(a1: A, a2: A): A
}
object IntWithAddition extends Monoid[Int] {
def unit: Int = 0
def multiply(a1: Int, a2: Int): Int = a1 + a2
}
object IntWithMultiplication extends Monoid[Int] {
def unit: Int = 1
def multiply(a1: Int, a2: Int): Int = a1 * a2
}
A monad in a category C consists of:
"myu"
"join"
identity functor
"eta"
"return"
such that
(associativity law)
(left and right identity laws)
trait Monad[F[_]] extends Functor[F] {
def unit(a: A): F[A]
def join(ffa: F[F[A]]): F[A]
def flatMap(fa: F[A])(f: A => F[A]): F[A] =
join(fa.map(f))
}
object MonadForList extends Monad[List] {
def unit(a: A): List[A] = List(a)
def join(lists: List[List[A]]) = lists.flatten
}
"myu"
"eta"
Category of endofunctors for category C
It's a monoidal category!
What does a monoid look like in this category?
Monoid in general
Monoid in Fun[C,C]
Monad
Monoid in Fun[C,C]