SlideShare a Scribd company logo
Category Theory In Scala


           Meetu Maltiar
        Principal Consultant
              Knoldus
Agenda


Category Theory the basics
Category Theory in Scala
Code Examples
Category

Pierce defines Category as comprising of:
●   A collection of objects
●   A collection of arrows (often called morphisms)
●   Operations assigning to each arrow f an object dom f, its
domain, and an object cod f, its codomain (f:A → B, where
dom f = A and cod f = B)
Category continued..

A composition operator assigning to each pair of arrows f and g with cod f
= dom g, a composite arrow g o f: dom f → cod g, satisfying the following
associative law:
for any arrows f:A → B, g:B → C and h:C → D
h o (g o f) = (h o g) o f


For each object A, an identity arrow idA: A → A satisfying the following
identity law:
for any arrow f:A → B, idB o f = f and f o idA = f
Category


Apples               Fruit

Banana               Vegetable

Brinjal




          f: A → B
Category Composition

Apples        Fruit
                          Living
Banana        Vegetable
                          Non Living
Brinjal




           g o f: A → C
Translating to Scala

We can define any function from a type A to type B as:
A => B here we have an example or morphism


For any function val foo: A => B = //Anything
We have type A as domain of function foo and type B as co-domain
of function foo
Scala Category Example

We can define composition of arrows or functions in Scala with
following REPL example

scala> val f: Int => String = _.toString
f: Int => String = <function1>

scala> val g: String => Int = _.length
g: String => Int = <function1>

scala> f compose g
res3: String => String = <function1>
Scala category identity continued
Identity law is a special version of a composition. Let's define function and play
them in REPL:

scala> val foo: Int => String = _.toString
foo: Int => String = <function1>

scala> val idInt: Int => Int = identity(_: Int)
idInt: Int => Int = <function1>

scala> val idString: String => String = identity(_: String)
idString: String => String = <function1>

scala> idString compose foo
res4: Int => String = <function1>

scala> foo compose idInt
res5: Int => String = <function1>
Category theory and PL

Do understanding Category Theory makes us understand PL's better?
If we just do Enterprise software development and do not want to go beyond
our comfort zone then answer is no.

Category Theory provides uniform model of set theory, algebra, logic and
computation.

Many concepts of Category theory maps nicely to structures of PL.

Categorical reasoning helps us to reason about programs. Some basic
structures in PL like product and sum types have their correspondences in
Category Theory.

There is a strong correspondence between typed lambda calculus and
cartesian closed categories
Properties of data type in CT
Consider the category of Products of elements. Take for example
of cartesian products from the category of sets.

A cartesian product of two sets A and B is defined by

A X B = {(a, b) | a belongs to A and b belongs to B}

For example if A = {1, 2} and B = {A, B}

A X B = {(1, A), (1, B), (2, A), (2, B)}

So here we have tuples or Pairs as objects in a Category
Properties of data type in CT ..

But what will be morphisms?


In case of products, the applicable arrows (or morphisms)
are the projection functions:
π1: A X B → A
π1: A X B → B
Properties of data type in CT ..
Now if we draw a Category diagram with C as a product type we
have two functions as projection functions:
1. f: C → A
2. g: C → B
and the product function is represented by: C → A X B It is defined
by:
<F, G>(x) = (f(x), g(x))
Diagram of CT

          C


     f              g
         ! [f,g]



A         AXB           B
    π1             π2
Diagram of CT
For every pair of vertices X and Y, all paths in the diagram from X
to Y are equal in the sense that each path forms an arrow and
these arrows are equal in category


For example the path from C to A is: <f,g> and π1 therefore
composition gives us:
π1 o <f,g> = f
Also path from C to B gives us: <f,g> and π2
π2 o <f,g> = g
Scala CT example

Lets now see how the laws of commutativity maps to Scala.

As a programmer we use the projection functions (_1 and _2) in
Scala Tuple2 on a regular basis

In the CT diagram we will see that we get additional insights in
abstraction and help understand mathematical properties of how
cartesian product of sets map translates to composition of
functions
Scala CT example...
scala> val ip = (10, "meetu")
ip: (Int, java.lang.String) = (10,meetu)

scala> val pi1: ((Int, String)) => Int = (p => p._1)
pi1: ((Int, String)) => Int = <function1>

scala> val pi2: ((Int, String)) => String = (p => p._2)
pi2: ((Int, String)) => String = <function1>

scala> val f: Int => Int = (_ * 2)
f: Int => Int = <function1>

scala> val g: Int => String = _.toString
g: Int => String = <function1>

scala> val `<f, g>`: Int => (Int, String) = (x => (f(x), g(x)))
<f, g>: Int => (Int, String) = <function1>

scala> pi1 compose `<f, g>`
res0: Int => Int = <function1>

scala> pi2 compose `<f, g>`
res1: Int => String = <function1>
Scala CT example
So we can claim from the commutativity of the diagram that:

pi1 compose `<f, g>` is type wise equal to f

pi2 compose `<f, g>` is type wise equal to g

Category theory says that morphism between C and A X B is
unique and that A X B is defined upto isomorphism.

Uniqueness is denoted by ! In diagram. This makes sense as well
because a pair can be unique
Interface driven modeling

Category Theory maps very closely to PL in the sense that it
focuses on arrows rather than objects corresponding to Interfaces

Pierce: CT typically “abstracts away from elements, treating
objects as black boxes with unimagined internal structure and
focusing attention on the properties of arrows between objects”

Learning CT enriches both CT and PL. For example if we know
what a Functor is in CT then we can easily make it generic enough
so that it can interact with other Functors
Thinking Generically
CT talks about objects and morphisms and how arrows compose.
A special kind of morphism is identity function in programming.

It is 0 in addition and 1 in multiplication

CT generalizes this concept by using same vocabulary (morphism)
to denote both stuff that does some operations and those that don't

For every object X, there exists a morphism idX: X → X called
identity morphism on X, such that for every morphism f: A → B we
have:
IdB o f = f = f o idA (used in monoids)
Duality


We have seen example of SumTypes for Product. If we look at the
CT diagram of Sum compared to Product we see that arrows are
reversed.

This is called a dual in CT. In Scala we model it by a Union Type
like Either where value of SumType comes either from left or right
What's Next

Functors
Monads
Scalaz

Resources:
1. Debasish Ghosh blog “Does Category Theory Makes you A
Better Programmer”
2. Heiko's blog on Category Theory
3. Runar video on Scalaz

More Related Content

PPTX
Scala fundamentals
PDF
Gentle Introduction to Scala
ODP
PHP Web Programming
PDF
Collections In Java
ODP
An introduction to SQLAlchemy
PDF
5 collection framework
PDF
Functional Domain Modeling - The ZIO 2 Way
PDF
Introducing Akka
Scala fundamentals
Gentle Introduction to Scala
PHP Web Programming
Collections In Java
An introduction to SQLAlchemy
5 collection framework
Functional Domain Modeling - The ZIO 2 Way
Introducing Akka

What's hot (20)

PPT
Concepts In Object Oriented Programming Languages
PDF
Tuples in Python
PPTX
ZIO: Powerful and Principled Functional Programming in Scala
PDF
ZIO-Direct - Functional Scala 2022
PPTX
Function C++
PPTX
Secrets of .NET Assemblies and Memory Management
PPTX
Introduction to Object Oriented Programming
PDF
Multiple Inheritance
PPTX
Purely Functional Data Structures in Scala
PDF
Arrays in Java | Edureka
PPTX
Kotlin as a Better Java
PPTX
Python in 30 minutes!
PDF
Python basics_ part1
PDF
C++ [ principles of object oriented programming ]
PPT
Java Basics V3
PPTX
Inheritance in java
PDF
ZIO Queue
PDF
Python programming : Inheritance and polymorphism
PPT
Super keyword.23
Concepts In Object Oriented Programming Languages
Tuples in Python
ZIO: Powerful and Principled Functional Programming in Scala
ZIO-Direct - Functional Scala 2022
Function C++
Secrets of .NET Assemblies and Memory Management
Introduction to Object Oriented Programming
Multiple Inheritance
Purely Functional Data Structures in Scala
Arrays in Java | Edureka
Kotlin as a Better Java
Python in 30 minutes!
Python basics_ part1
C++ [ principles of object oriented programming ]
Java Basics V3
Inheritance in java
ZIO Queue
Python programming : Inheritance and polymorphism
Super keyword.23
Ad

Similar to Scala categorytheory (20)

PDF
Monad Fact #4
PDF
Why functional programming and category theory strongly matters - Piotr Parad...
PDF
Why functional programming and category theory strongly matters
PDF
Monoids - Part 1 - with examples using Scalaz and Cats
PPT
Chpt-2-Functions-Seqs_v.5.ppt Function and Sequences
PPT
Lecture in Functions-Sequences and summations
PPT
lecture in Functions and Sequences and their properties
PDF
Power of functions in a typed world
PDF
lemh201 (1).pdfvjsbdkkdjfkfjfkffkrnfkfvfkrjof
PDF
Algebraic Data Types and Origami Patterns
PDF
Scala. Introduction to FP. Monads
PPTX
Category Theory in 10 Minutes
PPTX
Category theory for beginners
PDF
Frp2016 3
PDF
Introduction to Functional Programming with Scala
PPTX
Functions Defined on General Sets w Arrow Diagrams.pptx
PPTX
1_Representation_of_Functions.pptxshjsjsj
PPT
AXSARFERHBYUJKIOPOOIU7URTGERFEWRFDSFVDGREYGTH
PDF
List-based Monadic Computations for Dynamic Languages
PPTX
AIOU Code 803 Mathematics for Economists Semester Spring 2022 Assignment 2.pptx
Monad Fact #4
Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters
Monoids - Part 1 - with examples using Scalaz and Cats
Chpt-2-Functions-Seqs_v.5.ppt Function and Sequences
Lecture in Functions-Sequences and summations
lecture in Functions and Sequences and their properties
Power of functions in a typed world
lemh201 (1).pdfvjsbdkkdjfkfjfkffkrnfkfvfkrjof
Algebraic Data Types and Origami Patterns
Scala. Introduction to FP. Monads
Category Theory in 10 Minutes
Category theory for beginners
Frp2016 3
Introduction to Functional Programming with Scala
Functions Defined on General Sets w Arrow Diagrams.pptx
1_Representation_of_Functions.pptxshjsjsj
AXSARFERHBYUJKIOPOOIU7URTGERFEWRFDSFVDGREYGTH
List-based Monadic Computations for Dynamic Languages
AIOU Code 803 Mathematics for Economists Semester Spring 2022 Assignment 2.pptx
Ad

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
PPTX
Self-Healing Test Automation Framework - Healenium
PPTX
Kanban Metrics Presentation (Project Management)
PPTX
Java 17 features and implementation.pptx
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
PPTX
GraalVM - A Step Ahead of JVM Presentation
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
DAPR - Distributed Application Runtime Presentation
PPTX
Introduction to Azure Virtual WAN Presentation
PPTX
Introduction to Argo Rollouts Presentation
PPTX
Intro to Azure Container App Presentation
PPTX
Insights Unveiled Test Reporting and Observability Excellence
PPTX
Introduction to Splunk Presentation (DevOps)
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
PPTX
AWS: Messaging Services in AWS Presentation
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
PPTX
Managing State & HTTP Requests In Ionic.
Angular Hydration Presentation (FrontEnd)
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Self-Healing Test Automation Framework - Healenium
Kanban Metrics Presentation (Project Management)
Java 17 features and implementation.pptx
Chaos Mesh Introducing Chaos in Kubernetes
GraalVM - A Step Ahead of JVM Presentation
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
DAPR - Distributed Application Runtime Presentation
Introduction to Azure Virtual WAN Presentation
Introduction to Argo Rollouts Presentation
Intro to Azure Container App Presentation
Insights Unveiled Test Reporting and Observability Excellence
Introduction to Splunk Presentation (DevOps)
Code Camp - Data Profiling and Quality Analysis Framework
AWS: Messaging Services in AWS Presentation
Amazon Cognito: A Primer on Authentication and Authorization
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Managing State & HTTP Requests In Ionic.

Recently uploaded (20)

PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Cloud computing and distributed systems.
PPTX
Big Data Technologies - Introduction.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Approach and Philosophy of On baking technology
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
KodekX | Application Modernization Development
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
“AI and Expert System Decision Support & Business Intelligence Systems”
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Understanding_Digital_Forensics_Presentation.pptx
Cloud computing and distributed systems.
Big Data Technologies - Introduction.pptx
MYSQL Presentation for SQL database connectivity
Approach and Philosophy of On baking technology
Spectral efficient network and resource selection model in 5G networks
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Digital-Transformation-Roadmap-for-Companies.pptx
KodekX | Application Modernization Development
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication

Scala categorytheory

  • 1. Category Theory In Scala Meetu Maltiar Principal Consultant Knoldus
  • 2. Agenda Category Theory the basics Category Theory in Scala Code Examples
  • 3. Category Pierce defines Category as comprising of: ● A collection of objects ● A collection of arrows (often called morphisms) ● Operations assigning to each arrow f an object dom f, its domain, and an object cod f, its codomain (f:A → B, where dom f = A and cod f = B)
  • 4. Category continued.. A composition operator assigning to each pair of arrows f and g with cod f = dom g, a composite arrow g o f: dom f → cod g, satisfying the following associative law: for any arrows f:A → B, g:B → C and h:C → D h o (g o f) = (h o g) o f For each object A, an identity arrow idA: A → A satisfying the following identity law: for any arrow f:A → B, idB o f = f and f o idA = f
  • 5. Category Apples Fruit Banana Vegetable Brinjal f: A → B
  • 6. Category Composition Apples Fruit Living Banana Vegetable Non Living Brinjal g o f: A → C
  • 7. Translating to Scala We can define any function from a type A to type B as: A => B here we have an example or morphism For any function val foo: A => B = //Anything We have type A as domain of function foo and type B as co-domain of function foo
  • 8. Scala Category Example We can define composition of arrows or functions in Scala with following REPL example scala> val f: Int => String = _.toString f: Int => String = <function1> scala> val g: String => Int = _.length g: String => Int = <function1> scala> f compose g res3: String => String = <function1>
  • 9. Scala category identity continued Identity law is a special version of a composition. Let's define function and play them in REPL: scala> val foo: Int => String = _.toString foo: Int => String = <function1> scala> val idInt: Int => Int = identity(_: Int) idInt: Int => Int = <function1> scala> val idString: String => String = identity(_: String) idString: String => String = <function1> scala> idString compose foo res4: Int => String = <function1> scala> foo compose idInt res5: Int => String = <function1>
  • 10. Category theory and PL Do understanding Category Theory makes us understand PL's better? If we just do Enterprise software development and do not want to go beyond our comfort zone then answer is no. Category Theory provides uniform model of set theory, algebra, logic and computation. Many concepts of Category theory maps nicely to structures of PL. Categorical reasoning helps us to reason about programs. Some basic structures in PL like product and sum types have their correspondences in Category Theory. There is a strong correspondence between typed lambda calculus and cartesian closed categories
  • 11. Properties of data type in CT Consider the category of Products of elements. Take for example of cartesian products from the category of sets. A cartesian product of two sets A and B is defined by A X B = {(a, b) | a belongs to A and b belongs to B} For example if A = {1, 2} and B = {A, B} A X B = {(1, A), (1, B), (2, A), (2, B)} So here we have tuples or Pairs as objects in a Category
  • 12. Properties of data type in CT .. But what will be morphisms? In case of products, the applicable arrows (or morphisms) are the projection functions: π1: A X B → A π1: A X B → B
  • 13. Properties of data type in CT .. Now if we draw a Category diagram with C as a product type we have two functions as projection functions: 1. f: C → A 2. g: C → B and the product function is represented by: C → A X B It is defined by: <F, G>(x) = (f(x), g(x))
  • 14. Diagram of CT C f g ! [f,g] A AXB B π1 π2
  • 15. Diagram of CT For every pair of vertices X and Y, all paths in the diagram from X to Y are equal in the sense that each path forms an arrow and these arrows are equal in category For example the path from C to A is: <f,g> and π1 therefore composition gives us: π1 o <f,g> = f Also path from C to B gives us: <f,g> and π2 π2 o <f,g> = g
  • 16. Scala CT example Lets now see how the laws of commutativity maps to Scala. As a programmer we use the projection functions (_1 and _2) in Scala Tuple2 on a regular basis In the CT diagram we will see that we get additional insights in abstraction and help understand mathematical properties of how cartesian product of sets map translates to composition of functions
  • 17. Scala CT example... scala> val ip = (10, "meetu") ip: (Int, java.lang.String) = (10,meetu) scala> val pi1: ((Int, String)) => Int = (p => p._1) pi1: ((Int, String)) => Int = <function1> scala> val pi2: ((Int, String)) => String = (p => p._2) pi2: ((Int, String)) => String = <function1> scala> val f: Int => Int = (_ * 2) f: Int => Int = <function1> scala> val g: Int => String = _.toString g: Int => String = <function1> scala> val `<f, g>`: Int => (Int, String) = (x => (f(x), g(x))) <f, g>: Int => (Int, String) = <function1> scala> pi1 compose `<f, g>` res0: Int => Int = <function1> scala> pi2 compose `<f, g>` res1: Int => String = <function1>
  • 18. Scala CT example So we can claim from the commutativity of the diagram that: pi1 compose `<f, g>` is type wise equal to f pi2 compose `<f, g>` is type wise equal to g Category theory says that morphism between C and A X B is unique and that A X B is defined upto isomorphism. Uniqueness is denoted by ! In diagram. This makes sense as well because a pair can be unique
  • 19. Interface driven modeling Category Theory maps very closely to PL in the sense that it focuses on arrows rather than objects corresponding to Interfaces Pierce: CT typically “abstracts away from elements, treating objects as black boxes with unimagined internal structure and focusing attention on the properties of arrows between objects” Learning CT enriches both CT and PL. For example if we know what a Functor is in CT then we can easily make it generic enough so that it can interact with other Functors
  • 20. Thinking Generically CT talks about objects and morphisms and how arrows compose. A special kind of morphism is identity function in programming. It is 0 in addition and 1 in multiplication CT generalizes this concept by using same vocabulary (morphism) to denote both stuff that does some operations and those that don't For every object X, there exists a morphism idX: X → X called identity morphism on X, such that for every morphism f: A → B we have: IdB o f = f = f o idA (used in monoids)
  • 21. Duality We have seen example of SumTypes for Product. If we look at the CT diagram of Sum compared to Product we see that arrows are reversed. This is called a dual in CT. In Scala we model it by a Union Type like Either where value of SumType comes either from left or right
  • 22. What's Next Functors Monads Scalaz Resources: 1. Debasish Ghosh blog “Does Category Theory Makes you A Better Programmer” 2. Heiko's blog on Category Theory 3. Runar video on Scalaz