4. Functor
Given categories A and B, a functor F: A → B
consists of mappings F: Obj(A) → Obj(B)
and F: Fun(A) → Fun(B) ,
so that
F(idX
)=idF(X)
and F(f∘g)=F(f)∘F(g)
5. More Examples
● A= 3 , B=Sets; what is a functor 3 → Sets?
Have to define: sets F(0), F(1), F(2); functions F(f), F(g), F(gf)
● Any f:X→Y in category C is a functor from 2 to C.
6. Cartesian Product is a Functor
Fix an object A.
X ↦ X×A is a functor.
How does it work on functions?
f:X→Y ↦ f×idA
: X×A → Y×A
7. +1 is a Functor
In Sets, take X ↦ X+1. f: X→Y ↦ (f+1): X+1 → Y+1
This functor is called Option[T].
8. Category of Categories
Take functors F:A→B, G:B→C; their composition H=G∘F is also a functor.
H(idX
) = G(F(idX
)) = G(idF(X)
) = idG(F(X))
H(p∘q) = G(F(p∘q)) = G(F(p)∘F(q)) = G(F(p)) ∘G(F(q)) = H(p) ∘H(q)
Identity functor IdA
:A→A Id(f) = f
Cat - a category of all categories.
No barber problems, nobody shaves nobody.
9. Exponential Functor
A, B - objects in category C. BA
- an object of functions from A to B, if such
exists.
E.g. in Set, {f:A→B}.
In Scala In Java (Guava) (https://code.google.com/p/guava-
libraries/wiki/FunctionalExplained)
trait Function[X,Y] {
def apply(x:X): Y
}
interface Function<X,Y> {
Y apply(X x);
}
val len:Function[String, Int] = _.length Function<String, Integer> lengthFunction = new
Function<String, Integer>() {
public Integer apply(String string) {
return string.length();
}
};
10. Define Exponential via Currying
In Set, f:A→CB
≡ f’:A×B→C
f(x)(b) = f’(x,b)
Very similar to P⊢(Q→R) ≡ P∧Q ⊢ R
Actually… it’s the same thing.
Take posets, for example, Boolean lattice,
where a×b ≡ min(a,b) /*see lecture 7*/ ≡ a∧b
a∧b ≤ c ≡ a ≤ (b→c)
12. Example with Numbers
Category Z = (Z,≤); category Q = (Q,≤)
Inclusion iz
: Z ↣ Q - preserves order, so is a functor.
How about Q → Z? Upb: q ↦ Upb(q)
Upb(q) ≤ n /* this is in Z */ ≡ q ≤ n /* this is in Q */
Take composition q ↦ iZ
(Upb(q)), call it Mint.
We see two properties:
● q ≤ Mint(q)
● Mint(Mint(q)) ≤ Mint(q) /* actually equal */
13. Example with Lists
Category Scala
Take functor List.
We see two properties:
● singleton: X → List[X]
● flatten: List[List[X]] → List[X]
Do you see similarity?
14. Monad
* f:F(X)->G(X) is natural if for all p:X→ Y
Given a category C, an endofunctor M: C → C
is called a Monad if it has two features:
● unitX
: X → M(X)
● flattenX
: M(M(X)) → M(X)
These two functions should be natural*