It’s All About Morphisms It’s All About Morphisms
Uberto Barbini @ramtop https://medium.com/@ramtop
Its All About Morphisms Its All About Morphisms Uberto Barbini - - PowerPoint PPT Presentation
Its All About Morphisms Its All About Morphisms Uberto Barbini @ramtop https://medium.com/@ramtop Ab About m out me OOP OO progr grammer er Agi gile le TDD Funct nctio iona nal P PRo Rogr gramming ing Fina nance nce
Uberto Barbini @ramtop https://medium.com/@ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
progr grammer er OO OOP TDD Kot
lin Agi gile le Funct nctio iona nal P PRo Rogr gramming ing Blog: https://medium.com/ ramtop @ Twitter: ramtop @ Fina nance nce Ind ndust stry
#VoxxedVienna #morphisms #morphisms @ramtop
Ca Catego egory Mono noid id Funct nctor
Applic icative Mona nad Natural T l Transf nsformation
Morphism sms a s all th the w e way ay dow down...
Yone neda da
#VoxxedVienna #morphisms #morphisms @ramtop
I d I don’t
e about
Mona Monads ds, w why sh y shoul
I?
Precisely
Neith Neither do er do I what I ca care a abou
t is to defin to define s sys ystem em beh behaviou aviour
#VoxxedVienna #morphisms #morphisms @ramtop
This p presentati ntation w
ll b be a s a succ ccess i if mos most of t of you w you will ll not f not fall all a asleep This p presentati ntation w
ll b be a s a succ ccess i if mos most of t of you w you will ll not f not fall all a asleep
#VoxxedVienna #morphisms #morphisms @ramtop
You will consider that Functional Programming is about transformations and preserving properties. Not (only) lambdas and flatmap This p presentati ntation w
ll b be a s a succ ccess i if
#VoxxedVienna #morphisms #morphisms @ramtop
Wh What is at is t this is C Cat ateg egory thi
ngy?
Invented in 1940s “with the goal of understanding the processes that preserve mathematical st struc ucture.” “Category Theory is about rel elat ation between things” “General abstract no nonsense nsense”
#VoxxedVienna #morphisms #morphisms @ramtop
Once upon a time there was a Category of Stuffed Toys and a Category of Tigers...
#VoxxedVienna #morphisms #morphisms @ramtop
A Cat Categ egory is is defin efined ed in in 5 5 step eps:
#VoxxedVienna #morphisms #morphisms @ramtop
A Cat Categ egory is is defin efined ed in in 5 5 step eps:
#VoxxedVienna #morphisms #morphisms @ramtop
A Cat Categ egory is is defin efined ed in in 5 5 step eps:
#VoxxedVienna #morphisms #morphisms @ramtop
A Cat Categ egory is is defin efined ed in in 5 5 step eps:
#VoxxedVienna #morphisms #morphisms @ramtop
(an arro (an arrow po pointing ting t to it
elf)
A Cat Categ egory is is defin efined ed in in 5 5 step eps:
#VoxxedVienna #morphisms #morphisms @ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
Tube Map: Objects stations
travel routes
Arrow composition is travelling along the line Identity Arrow is staying in the same station
#VoxxedVienna #morphisms #morphisms @ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
Ca Catego egory Monoi noid Funct nctor
Appli lica cativ ive Mona nad Natural T l Transf nsformatio ion Yoned neda
#VoxxedVienna #morphisms #morphisms @ramtop
New ewOr Order Rea Ready dy Ca Cance ncell lled ed Ret Returned ed Dispatch ched Closed ed
https://skillsmatter.com/skillscasts/11486-functional-cqrs AddItem AddItem Cancel Cancel Dispatch Dispatch Return Return Close Close
#VoxxedVienna #morphisms #morphisms @ramtop
Func Functional Pro ional Program ramming ming is is als also a C
ateg egory ry
Each programming language has a Category: Types pes are the objects and Fun unct ctions are the morphisms. Part rtial fu l functions don’t have a defined return for all inputs. In reality all programming functions are partial: they can raise Exceptions or never end. They always have an hidden return of Bottom Type ( ) ⊥* ⊥*
#VoxxedVienna #morphisms #morphisms @ramtop
Ob Objec ect O Oriented ented Fu Funct ctional nal Living Bacter ng Bacteria Gea ears and and P Pipes es Op Opaqu aque Trans anspar arent nt Hi Hidden St n State ate Immutabl table Stat State Int nterfaces ces Type C Clas asses
#VoxxedVienna #morphisms #morphisms @ramtop
Kotl
n for f
unctional p
rammi ming ng
#VoxxedVienna #morphisms #morphisms @ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
KEEP-87 TypeClasses
#VoxxedVienna #morphisms #morphisms @ramtop
For the Category morphisms to work in programming we need Puri rity and Im Immutabi abili lity. But they are not a goal per se, only a necessity for the main goal: co compo posi sition and transf sform rmation. Ultimately everything is converted in assem assembly bly which is neither pure nor immutable. We need those quality
posed sed code
#VoxxedVienna #morphisms #morphisms @ramtop
What about the category of morphisms of a category? Are they composable? It’s a Category with a single Object and lots of Morphisms A Ca Categor egory y wi with th only one
Objec ect t is a Mo Monoi noid
#VoxxedVienna #morphisms #morphisms @ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
A type class with two methods combine monoid append
neutral element
empty <> x = x -- left identity x <> empty = x -- right identity
#VoxxedVienna #morphisms #morphisms @ramtop
List<A> is just an abstract type to build List<Int> List<String> List<User> etc.
#VoxxedVienna #morphisms #morphisms @ramtop
Cat and Dogs can be treated as Animals
witho hout hi hiding t g thei eir t r type pes: Cats and Dogs can both form couples but cats can mate
You cannot represent that with interfaces.
#VoxxedVienna #morphisms #morphisms @ramtop
Typecl Typeclas ass Ins Instanc ances es
has an (or more) instance of Monoid one of Functor and
a singletons specific implementation.
evaluation, for example because of concurrency
#VoxxedVienna #morphisms #morphisms @ramtop
Enough h talk, , let let’s ’s see ee the he co code! e!
Mono noid id TypeCla Class Inst nstances. nces... ...Give u e us the co combi bine e ne extens nsion
funct nctio ion
#VoxxedVienna #morphisms #morphisms @ramtop
The f e fut utur ure (?) (?)
extension interface Monoid<T> { infix fun T.add(t: T): T } extension object IntMonoid: Monoid<Int> { inline fun Int.add(t: Int) = this + t } inline fun <T> sum(t1: T, t2: T, t3: T, with Monoid<T>) = t1 add t2 add t3 fun main() { sum(1, 2, 3) //no boxing because of inlining }
#VoxxedVienna #morphisms #morphisms @ramtop
Trans ransform
ers a a.k.a. F .a. Functors
Very Important!!
#VoxxedVienna #morphisms #morphisms @ramtop
Functors can map both object ects (types) and morph rphism (functions) between two categories Functors map must preserve the structure and some properties But can also work inside the same category (End Endofu funct nctors rs)
#VoxxedVienna #morphisms #morphisms @ramtop
Functor is a TypeClass with a Map function that works like this. Id is the identity function. map id x = x map (g <> f) = map g <> map f) Passing the ID function must return the original value Map must honour associativity of two functions
#VoxxedVienna #morphisms #morphisms @ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
Fail ilure w without E Excep ceptio ion Kee eep a a cont ntex ext and M nd Map o
eratio ion n
n `it
#VoxxedVienna #morphisms #morphisms @ramtop
Functo Functors rs are al are also Fo Forklif ifts ts
val lifted = Try.functor().lift {x:String -> x.toInt()} lifted(Try.Success("42")) //Try.Success(42) Lift a function from A --> B to F<A> --> F<B>
#VoxxedVienna #morphisms #morphisms @ramtop
Yoneda's lemma concerns functors from a fixed category C to the category of sets, Set. If C is a locally small category (i.e. the hom- sets are actual sets and not proper classes), then each object A of C gives rise to a natural functor to Set called a hom-functor.
#VoxxedVienna #morphisms #morphisms @ramtop
F<?>.map(A→B): F<B> (? must be A) The actual implementation is useful to compose of mappings without executing until we decide co combine bine a all l the m maps in s in
ne a and nd t then en apply ly i it. No co
ies o
List ist
#VoxxedVienna #morphisms #morphisms @ramtop
Na Natural ural T Trans ransfo forma rmations ions
A nat atural t ral tran ransf sform rmat ation provides a way of transforming one functor into another while respecting the internal structure of the categories involved. Transforming Data → Functions Data → Functions Transforming Functions → Functors Functions → Functors Transforming Functors → Natural Functors → Natural Transformations Transformations
#VoxxedVienna #morphisms #morphisms @ramtop
Natural Tr Transfo forma mations
#VoxxedVienna #morphisms #morphisms @ramtop
val list = Try {"3".toInt()}.toOption().toList() //[3] val fail = Try {"xyz".toInt()}.toOption().toList() //[]
#VoxxedVienna #morphisms #morphisms @ramtop
We can imagine 2 ways to combine 2 functors F + F = F F<f> map F<a> = F<f(a)>
F * F = F flatmap (a → F<a → F<a>>) = F a
#VoxxedVienna #morphisms #morphisms @ramtop
funct ction inside another Functor
function with x-1 params.
pply:
#VoxxedVienna #morphisms #morphisms @ramtop
Try A y Appli plicat cative F Fun uncto tor
Sil Silly ly e exa xample le of
funct nctio ion n that ca can raise a ise an E n Excep ceptio ion Exce ceptio ion r n raised! d!
#VoxxedVienna #morphisms #morphisms @ramtop
Monoid instance?
A Monad is just a Monoid in the category of Endofunctors, what's the problem?
#VoxxedVienna #morphisms #morphisms @ramtop
Mo Monad Rec nad Recipe ipe
#VoxxedVienna #morphisms #morphisms @ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
From here:
val university: IO<University> = getStudent("John Smith").flatMap { student -> getUniversity(student.universityId).flatMap { university -> getDean(university.deanId) } }
To here:
val university: IO<University> = IO.monad().binding { val student = getStudent("John Smith").bind() val university = getUniversity(student.universityId).bind() val dean = getDean(university.deanId).bind() dean }
#VoxxedVienna #morphisms #morphisms @ramtop
Per Perfec ectly Pur ly Pure e Pr Progr
ams s are e Per erfec ectly ly U Useless seless
E n t e r E f f e c t s
#VoxxedVienna #morphisms #morphisms @ramtop
De Depende dency In y Inje jecti tion
cou
sy of
eader Mon
d
What’s h happen if n if u user ca canno nnot be be f fetch ched ed? Runs h ns here
fun getUser(userId:String):Reader Reader<Context, User> { fun getCommonFriends(u1: User, u2: User): Reader Reader<Context, List<User>>
#VoxxedVienna #morphisms #morphisms @ramtop
All Monads are also Functors and Applicative, but the opposite is not true. Each Monad as it’s specific logic on top
These are already available in many libraries but you can extend and create your own.
#VoxxedVienna #morphisms #morphisms @ramtop
Why s y studyi ying C ng Categories ategories?
Morphisms allows you to work at compile time with your Do Domain K Knowled wledge ge Learn how to co compo pose functions and pres preserve properties Monads and other typeclasses should em emerge erge from your code, not the other way round Learn a common t term erminolo logy gy and the reasons behind that
#VoxxedVienna #morphisms #morphisms @ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
Real World Ex eal World Exam amples ples
Web Se Server a er as a f func uncti tion github.com/http4k/http4k Func uncti tiona nal D Doma
n Design gn github.com/uberto/anticapizzeria
#VoxxedVienna #morphisms #morphisms @ramtop
To l learn m earn more: re:
Category Theory for Programmers bartoszmilewski.com Cats in scala typelevel.org/cats Arrow in Kotlin arrow-kt.io
If yo f you enj enjoyed yed pleas please f e follo llow w me o e on t n twit witter and medi ter and medium ram ramtop @ramtoq @ramtoq
#VoxxedVienna #morphisms #morphisms @ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
#VoxxedVienna #morphisms #morphisms @ramtop
Category of our types
constructor in the same category of a (the type system category)
them!
#VoxxedVienna #morphisms #morphisms @ramtop
In Java we cannot abstract at more than one level like List<A<B>>
But in Functional programming makes sense generalise over the container or context like: X<A> + f(A)->B = X<B>
#VoxxedVienna #morphisms #morphisms @ramtop
"The he diagra gram co commutes es" means that the map produced by following any path through the diagram is the same.
#VoxxedVienna #morphisms #morphisms @ramtop
Li List A App ppli licati cative
Can y you gu guess ess h how
it w wor
Transf nsform a st standa ndard L d List ist i in a n a Arrow
List ist ( (Lis istK)
#VoxxedVienna #morphisms #morphisms @ramtop
List Ma Map2
Exact ctly ly s same r e resu esult lt
#VoxxedVienna #morphisms #morphisms @ramtop
Read eader: er: A A Func Functor on f r on functio unctions ns
Val userId = 123 val reader = Reader{dbUrl:String -> DbConn(dbUrl)} val name = reader.run("myDbConn") .map{it.getUser(userId) } .map{it.name} .value() //"Joe"
#VoxxedVienna #morphisms #morphisms @ramtop
Pu Purit ity Bubbles les + + Eve vents = Act ctors
#VoxxedVienna #morphisms #morphisms @ramtop "Rather than thinking about function pu puri rity as a go goal, you have to think about which pro propert perties es you want your program to pres preserv erve." @raulraja
Perf erfect ectly ly Pu Pure Pro re Progra rams ms are re Per Perfect ectly ly Us Useless eless
#VoxxedVienna #morphisms #morphisms @ramtop
London Tu Tube e Map is is a Mo Monoid!
(if you squint hard enough)
#VoxxedVienna #morphisms #morphisms @ramtop
Ok… bu but w t why using ng a O a Obj bject O ct Ori riented ted La Lang ngua uage f for
Functi tion
Prog
ramm mming at at al all? l?
#VoxxedVienna #morphisms #morphisms @ramtop
why fu function ctional l prog rogram rammin ing?
More composition Less boilerplate Less repetitions Less bugs Less need for tests Easier concurrency Less sugar Different thinking Performance issues Complex state More precision Different testing style
VS VS
#VoxxedVienna #morphisms #morphisms @ramtop
Monads Transformers
#VoxxedVienna #morphisms #morphisms @ramtop
Validated example
#VoxxedVienna #morphisms #morphisms @ramtop
Original problem: Monads don’t allow for concurrency Arrows can be useful in Reactive Functional Programming Kleisli is a type of Arrow for a Monadic context It’s old ReaderT actually
#VoxxedVienna #morphisms #morphisms @ramtop
Arrows
#VoxxedVienna #morphisms #morphisms @ramtop
CandyDispenser
(Seed, Candy)
State
(Dispenser, [Input]) (Dispenser, [Candy])
#VoxxedVienna #morphisms #morphisms @ramtop
Functor F from category D to C Functor G from C to D Every adjunction 〈 F, G, , ε, θ η 〉 gives rise to an associated monad 〈 T, , η μ 〉 in the category D.