Its All About Morphisms Its All About Morphisms Uberto Barbini - - PowerPoint PPT Presentation

it s all about morphisms it s all about morphisms
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

It’s All About Morphisms It’s All About Morphisms

Uberto Barbini @ramtop https://medium.com/@ramtop

slide-2
SLIDE 2

#VoxxedVienna #morphisms #morphisms @ramtop

Ab About m

  • ut me

progr grammer er OO OOP TDD Kot

  • tli

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

slide-3
SLIDE 3

#VoxxedVienna #morphisms #morphisms @ramtop

Map Map of th

  • f this p

s prese sentation ntation

Ca Catego egory Mono noid id Funct nctor

  • r

Applic icative Mona nad Natural T l Transf nsformation

  • n

Morphism sms a s all th the w e way ay dow down...

Yone neda da

slide-4
SLIDE 4

#VoxxedVienna #morphisms #morphisms @ramtop

I d I don’t

  • n’t care

e about

  • ut

Mona Monads ds, w why sh y shoul

  • uld I?

I?

Precisely

Neith Neither do er do I what I ca care a abou

  • ut is

t is to defin to define s sys ystem em beh behaviou aviour

slide-5
SLIDE 5

#VoxxedVienna #morphisms #morphisms @ramtop

This p presentati ntation w

  • n will

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

  • n will

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

slide-6
SLIDE 6

#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

  • n will

ll b be a s a succ ccess i if

slide-7
SLIDE 7

#VoxxedVienna #morphisms #morphisms @ramtop

Wh What is at is t this is C Cat ateg egory thi

  • ry thingy

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”

slide-8
SLIDE 8

#VoxxedVienna #morphisms #morphisms @ramtop

Once upon a time there was a Category of Stuffed Toys and a Category of Tigers...

slide-9
SLIDE 9

#VoxxedVienna #morphisms #morphisms @ramtop

1) A collection 1) A collection

  • f Objects
  • f Objects

A Cat Categ egory is is defin efined ed in in 5 5 step eps:

slide-10
SLIDE 10

#VoxxedVienna #morphisms #morphisms @ramtop

2) A c 2) A collection

  • llection
  • f Arrows
  • f Arrows

A Cat Categ egory is is defin efined ed in in 5 5 step eps:

slide-11
SLIDE 11

#VoxxedVienna #morphisms #morphisms @ramtop

3) Each A ) Each Arrow rrow works

  • rks on
  • n 2

2 Objects Objects

A Cat Categ egory is is defin efined ed in in 5 5 step eps:

slide-12
SLIDE 12

#VoxxedVienna #morphisms #morphisms @ramtop

4) Arrows can 4) Arrows can be combined be combined

A Cat Categ egory is is defin efined ed in in 5 5 step eps:

slide-13
SLIDE 13

#VoxxedVienna #morphisms #morphisms @ramtop

5) Each Object 5) Each Object has an Identity has an Identity

(an arro (an arrow po pointing ting t to it

  • itsel

elf)

A Cat Categ egory is is defin efined ed in in 5 5 step eps:

slide-14
SLIDE 14

#VoxxedVienna #morphisms #morphisms @ramtop

slide-15
SLIDE 15

#VoxxedVienna #morphisms #morphisms @ramtop

A Category Exa A Category Examp mple

Tube Map: Objects stations

  • Arrows

travel routes

  • Each Arrows connect 2 stations

Arrow composition is travelling along the line Identity Arrow is staying in the same station

slide-16
SLIDE 16

#VoxxedVienna #morphisms #morphisms @ramtop

London London Tub ube Category Category

slide-17
SLIDE 17

#VoxxedVienna #morphisms #morphisms @ramtop

This is pr pres esentation entation is a is a Categor tegory y as as well! ell!

Ca Catego egory Monoi noid Funct nctor

  • r

Appli lica cativ ive Mona nad Natural T l Transf nsformatio ion Yoned neda

slide-18
SLIDE 18

#VoxxedVienna #morphisms #morphisms @ramtop

Eve Event nt Source Ca Source Cate tegor

  • ry

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

slide-19
SLIDE 19

#VoxxedVienna #morphisms #morphisms @ramtop

Func Functional Pro ional Program ramming ming is is als also a C

  • a Cat

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 ( ) ⊥* ⊥*

slide-20
SLIDE 20

#VoxxedVienna #morphisms #morphisms @ramtop

Change of mindset!

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

slide-21
SLIDE 21

#VoxxedVienna #morphisms #morphisms @ramtop

Kotl

  • tlin f

n for f

  • r functi

unctional p

  • nal program

rammi ming ng

  • Nullable and not-nullable types
  • Type Aliases
  • Class extensions
  • Tail recursion
  • Pattern matching (when)
  • Arrow-kt bindinds with coroutines
  • Arrow-kt Typeclasses (?)
slide-22
SLIDE 22

#VoxxedVienna #morphisms #morphisms @ramtop

arrow-kt.io

slide-23
SLIDE 23

#VoxxedVienna #morphisms #morphisms @ramtop

KEEP-87 TypeClasses

slide-24
SLIDE 24

#VoxxedVienna #morphisms #morphisms @ramtop

Pur Purity ity and and Imm Immutab utability ility

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

  • nly for expo

posed sed code

slide-25
SLIDE 25

#VoxxedVienna #morphisms #morphisms @ramtop

Monoid Monoid

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

  • ne Obj

Objec ect t is a Mo Monoi noid

slide-26
SLIDE 26

#VoxxedVienna #morphisms #morphisms @ramtop

slide-27
SLIDE 27

#VoxxedVienna #morphisms #morphisms @ramtop

Progr Programming ing wi with th Monoids

  • noids

A type class with two methods combine monoid append

  • empty

neutral element

  • (x <> y) <> z = x <> (y <> z) -- associativity

empty <> x = x -- left identity x <> empty = x -- right identity

slide-28
SLIDE 28

#VoxxedVienna #morphisms #morphisms @ramtop

Gener neric ics Type Contructors ype Contructors

List<A> is just an abstract type to build List<Int> List<String> List<User> etc.

slide-29
SLIDE 29

#VoxxedVienna #morphisms #morphisms @ramtop

Type Cla e Class ss vs vs Inter nterfa face ce

  • Interfaces “unify” different types:

Cat and Dogs can be treated as Animals

  • Type Classes “group” types with similar behaviour, wi

witho hout hi hiding t g thei eir t r type pes: Cats and Dogs can both form couples but cats can mate

  • nly with cats and dogs with dogs.

You cannot represent that with interfaces.

slide-30
SLIDE 30

#VoxxedVienna #morphisms #morphisms @ramtop

Typecl Typeclas ass Ins Instanc ances es

  • Typeclasses work with instances (like a singleton)
  • List is not a Monoid nor a Functor nor a Monad but it

has an (or more) instance of Monoid one of Functor and

  • ne of Monad
  • Technically we implement instances as an interface with

a singletons specific implementation.

  • We can have different implementation for difference in

evaluation, for example because of concurrency

slide-31
SLIDE 31

#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

  • n

funct nctio ion

slide-32
SLIDE 32

#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 }

slide-33
SLIDE 33

#VoxxedVienna #morphisms #morphisms @ramtop

Trans ransform

  • rmers

ers a a.k.a. F .a. Functors

  • rs

Very Important!!

slide-34
SLIDE 34

#VoxxedVienna #morphisms #morphisms @ramtop

Functors unctors

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)

slide-35
SLIDE 35

#VoxxedVienna #morphisms #morphisms @ramtop

Functor Laws unctor Laws

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

slide-36
SLIDE 36

#VoxxedVienna #morphisms #morphisms @ramtop

slide-37
SLIDE 37

#VoxxedVienna #morphisms #morphisms @ramtop

Try Functor ry Functor

Fail ilure w without E Excep ceptio ion Kee eep a a cont ntex ext and M nd Map o

  • per

eratio ion n

  • n `it

n `it

slide-38
SLIDE 38

#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>

slide-39
SLIDE 39

#VoxxedVienna #morphisms #morphisms @ramtop

Yoneda Yoneda L Lem emma ma

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.

slide-40
SLIDE 40

#VoxxedVienna #morphisms #morphisms @ramtop

Yoneda Yoneda L Lem emma ma

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

ne a and nd t then en apply ly i it. No co

  • copie

ies o

  • f L

List ist

slide-41
SLIDE 41

#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

slide-42
SLIDE 42

#VoxxedVienna #morphisms #morphisms @ramtop

Natural Tr Transfo forma mations

slide-43
SLIDE 43

#VoxxedVienna #morphisms #morphisms @ramtop

Natur Natural al Trans Transform

  • rmati

tions

  • ns

val list = Try {"3".toInt()}.toOption().toList() //[3] val fail = Try {"xyz".toInt()}.toOption().toList() //[]

slide-44
SLIDE 44

#VoxxedVienna #morphisms #morphisms @ramtop

Com

  • mbini

ining Functors ng Functors

We can imagine 2 ways to combine 2 functors F + F = F F<f> map F<a> = F<f(a)>

  • r

F * F = F flatmap (a → F<a → F<a>>) = F a

slide-45
SLIDE 45

#VoxxedVienna #morphisms #morphisms @ramtop

Applic Applicative ative Functors unctors

  • We can combine a value inside a Functor with a fu

funct ction inside another Functor

  • If the function want more than 1 param, it will return a

function with x-1 params.

  • Applicative can apply

pply:

  • F<A> applied to F<A->B> to create F<B>
slide-46
SLIDE 46

#VoxxedVienna #morphisms #morphisms @ramtop

Try A y Appli plicat cative F Fun uncto tor

Sil Silly ly e exa xample le of

  • f f

funct nctio ion n that ca can raise a ise an E n Excep ceptio ion Exce ceptio ion r n raised! d!

slide-47
SLIDE 47

#VoxxedVienna #morphisms #morphisms @ramtop

The M wor word... ...

  • What about a category of (endo)functors?
  • Some functors have a monoid instance, others not.
  • How can we call the Category of Endofunctors with a

Monoid instance?

A Monad is just a Monoid in the category of Endofunctors, what's the problem?

slide-48
SLIDE 48

#VoxxedVienna #morphisms #morphisms @ramtop

Mo Monad Rec nad Recipe ipe

slide-49
SLIDE 49

#VoxxedVienna #morphisms #morphisms @ramtop

Monads Allow Sequences

  • f Instructions
slide-50
SLIDE 50

#VoxxedVienna #morphisms #morphisms @ramtop

Monads Monads Bi Binding nding

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 }

slide-51
SLIDE 51

#VoxxedVienna #morphisms #morphisms @ramtop

Functiona nctional l Pr Progr

  • gramm

amming ing Di Dilemm lemma: a:

Per Perfec ectly Pur ly Pure e Pr Progr

  • gram

ams s are e Per erfec ectly ly U Useless seless

E n t e r E f f e c t s

slide-52
SLIDE 52

#VoxxedVienna #morphisms #morphisms @ramtop

De Depende dency In y Inje jecti tion

  • n

cou

  • urtesy

sy of

  • f Reade

eader Mon

  • nad

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>>

slide-53
SLIDE 53

#VoxxedVienna #morphisms #morphisms @ramtop

Monads

  • nads Zoo

Zoo

All Monads are also Functors and Applicative, but the opposite is not true. Each Monad as it’s specific logic on top

  • f the Monads Laws

These are already available in many libraries but you can extend and create your own.

  • Option
  • Try
  • List
  • Either
  • Reader
  • Writer
  • State
  • IO
  • Free
slide-54
SLIDE 54

#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

slide-55
SLIDE 55

#VoxxedVienna #morphisms #morphisms @ramtop

How How to us to use mor

  • rphisms

phisms in n real l world

  • rld pr

program

  • grams?

s?

slide-56
SLIDE 56

#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

  • main D

n Design gn github.com/uberto/anticapizzeria

slide-57
SLIDE 57

#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

slide-58
SLIDE 58

#VoxxedVienna #morphisms #morphisms @ramtop

slide-59
SLIDE 59

#VoxxedVienna #morphisms #morphisms @ramtop

slide-60
SLIDE 60

#VoxxedVienna #morphisms #morphisms @ramtop

slide-61
SLIDE 61

#VoxxedVienna #morphisms #morphisms @ramtop

slide-62
SLIDE 62

#VoxxedVienna #morphisms #morphisms @ramtop

Endofunc ndofunctor tors

  • In programming we only work with Endofunctors in the

Category of our types

  • Endofunctor map a => F a where F a is a type

constructor in the same category of a (the type system category)

  • Endofunctors are very important because we can compose

them!

slide-63
SLIDE 63

#VoxxedVienna #morphisms #morphisms @ramtop

Higher Higher Kinded inded Type ypes

In Java we cannot abstract at more than one level like List<A<B>>

  • r ignoring the second level List<A<?>>

But in Functional programming makes sense generalise over the container or context like: X<A> + f(A)->B = X<B>

slide-64
SLIDE 64

#VoxxedVienna #morphisms #morphisms @ramtop

Mona Monads ds Laws ws

"The he diagra gram co commutes es" means that the map produced by following any path through the diagram is the same.

slide-65
SLIDE 65

#VoxxedVienna #morphisms #morphisms @ramtop

Li List A App ppli licati cative

Can y you gu guess ess h how

  • w it

it w wor

  • rk?

Transf nsform a st standa ndard L d List ist i in a n a Arrow

  • w L

List ist ( (Lis istK)

slide-66
SLIDE 66

#VoxxedVienna #morphisms #morphisms @ramtop

List Ma Map2

Exact ctly ly s same r e resu esult lt

slide-67
SLIDE 67

#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"

slide-68
SLIDE 68

#VoxxedVienna #morphisms #morphisms @ramtop

Pu Purit ity Bubbles les + + Eve vents = Act ctors

slide-69
SLIDE 69

#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

slide-70
SLIDE 70

#VoxxedVienna #morphisms #morphisms @ramtop

London Tu Tube e Map is is a Mo Monoid!

(if you squint hard enough)

slide-71
SLIDE 71

#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

  • r F

Functi tion

  • nal

Prog

  • gra

ramm mming at at al all? l?

slide-72
SLIDE 72

#VoxxedVienna #morphisms #morphisms @ramtop

Conclusions: Conclusions:

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

slide-73
SLIDE 73

#VoxxedVienna #morphisms #morphisms @ramtop

Monads Transformers

  • Monads don’t compose
slide-74
SLIDE 74

#VoxxedVienna #morphisms #morphisms @ramtop

Validated example

  • Better than Try
slide-75
SLIDE 75

#VoxxedVienna #morphisms #morphisms @ramtop

Klei leisli li Arrows

  • ws

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

slide-76
SLIDE 76

#VoxxedVienna #morphisms #morphisms @ramtop

Arrows

slide-77
SLIDE 77

#VoxxedVienna #morphisms #morphisms @ramtop

CandyDispenser

  • Code example
  • Let’s bring all together
  • We have a function Seed

(Seed, Candy)

  • Another one (State, Input)

State

  • How can we combine them?
  • We want

(Dispenser, [Input]) (Dispenser, [Candy])

slide-78
SLIDE 78

#VoxxedVienna #morphisms #morphisms @ramtop

Adjoint Adjoint Func Functor tors

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.