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

What's hot

Left and Right Folds - Comparison of a mathematical definition and a programm...
Left and Right Folds- Comparison of a mathematical definition and a programm...Left and Right Folds- Comparison of a mathematical definition and a programm...
Left and Right Folds - Comparison of a mathematical definition and a programm...
Philip Schwarz
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
Philip Schwarz
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Elizabeth alexander
 
Java: Primitive Data Types
Java: Primitive Data TypesJava: Primitive Data Types
Java: Primitive Data Types
Tareq Hasan
 
Category Theory in 10 Minutes
Category Theory in 10 MinutesCategory Theory in 10 Minutes
Category Theory in 10 Minutes
Jordan Parmer
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...
Philip Schwarz
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
intelliyole
 
polymorphism
polymorphism polymorphism
polymorphism
Imtiaz Hussain
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Philip Schwarz
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
Philip Schwarz
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
The Sieve of Eratosthenes - Part 1
The Sieve of Eratosthenes - Part 1The Sieve of Eratosthenes - Part 1
The Sieve of Eratosthenes - Part 1
Philip Schwarz
 
ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022
Alexander Ioffe
 
Scala Intro
Scala IntroScala Intro
The Expression Problem - Part 1
The Expression Problem - Part 1The Expression Problem - Part 1
The Expression Problem - Part 1
Philip Schwarz
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
Philip Schwarz
 
Java String class
Java String classJava String class
Java String class
DrRajeshreeKhande
 
Applicative Functor
Applicative FunctorApplicative Functor
Applicative Functor
Philip Schwarz
 
Clean code
Clean codeClean code
Clean code
ifnu bima
 

What's hot (20)

Left and Right Folds - Comparison of a mathematical definition and a programm...
Left and Right Folds- Comparison of a mathematical definition and a programm...Left and Right Folds- Comparison of a mathematical definition and a programm...
Left and Right Folds - Comparison of a mathematical definition and a programm...
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Java: Primitive Data Types
Java: Primitive Data TypesJava: Primitive Data Types
Java: Primitive Data Types
 
Category Theory in 10 Minutes
Category Theory in 10 MinutesCategory Theory in 10 Minutes
Category Theory in 10 Minutes
 
The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...The aggregate function - from sequential and parallel folds to parallel aggre...
The aggregate function - from sequential and parallel folds to parallel aggre...
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
polymorphism
polymorphism polymorphism
polymorphism
 
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
Nat, List and Option Monoids -from scratch -Combining and Folding -an exampleNat, List and Option Monoids -from scratch -Combining and Folding -an example
Nat, List and Option Monoids - from scratch - Combining and Folding - an example
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
The Sieve of Eratosthenes - Part 1
The Sieve of Eratosthenes - Part 1The Sieve of Eratosthenes - Part 1
The Sieve of Eratosthenes - Part 1
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
The Expression Problem - Part 1
The Expression Problem - Part 1The Expression Problem - Part 1
The Expression Problem - Part 1
 
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
The Sieve of Eratosthenes - Part II - Genuine versus Unfaithful Sieve - Haske...
 
Java String class
Java String classJava String class
Java String class
 
Applicative Functor
Applicative FunctorApplicative Functor
Applicative Functor
 
Clean code
Clean codeClean code
Clean code
 

Similar to Scala categorytheory

Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
Philip Schwarz
 
Why functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersWhy functional programming and category theory strongly matters
Why functional programming and category theory strongly matters
Piotr Paradziński
 
Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...
Scalac
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Debasish Ghosh
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsVasil Remeniuk
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
Kirill Kozlov
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginners
kenbot
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
Kirill Kozlov
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic Languages
Wim Vanderbauwhede
 
AIOU Code 803 Mathematics for Economists Semester Spring 2022 Assignment 2.pptx
AIOU Code 803 Mathematics for Economists Semester Spring 2022 Assignment 2.pptxAIOU Code 803 Mathematics for Economists Semester Spring 2022 Assignment 2.pptx
AIOU Code 803 Mathematics for Economists Semester Spring 2022 Assignment 2.pptx
Zawarali786
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
Angelo Corsaro
 
Ch5b.pdf
Ch5b.pdfCh5b.pdf
Function
Function Function
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative Programmers
Chris
 
Function notation by sadiq
Function notation by sadiqFunction notation by sadiq
Function notation by sadiq
Sadiq Hussain
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
Daniele Pozzobon
 
Functors
FunctorsFunctors
Functors
Philip Schwarz
 
Integration
IntegrationIntegration
Integration
sakhi pathak
 

Similar to Scala categorytheory (20)

Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
 
Why functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersWhy functional programming and category theory strongly matters
Why functional programming and category theory strongly matters
 
Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami Patterns
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginners
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic Languages
 
AIOU Code 803 Mathematics for Economists Semester Spring 2022 Assignment 2.pptx
AIOU Code 803 Mathematics for Economists Semester Spring 2022 Assignment 2.pptxAIOU Code 803 Mathematics for Economists Semester Spring 2022 Assignment 2.pptx
AIOU Code 803 Mathematics for Economists Semester Spring 2022 Assignment 2.pptx
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Ch5b.pdf
Ch5b.pdfCh5b.pdf
Ch5b.pdf
 
Function
Function Function
Function
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative Programmers
 
Function notation by sadiq
Function notation by sadiqFunction notation by sadiq
Function notation by sadiq
 
Still works
Still worksStill works
Still works
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 
Functors
FunctorsFunctors
Functors
 
Integration
IntegrationIntegration
Integration
 

More from Knoldus Inc.

Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
Knoldus Inc.
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
Knoldus Inc.
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
Knoldus Inc.
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
Knoldus Inc.
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
Knoldus Inc.
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
Knoldus Inc.
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
Knoldus Inc.
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
Knoldus Inc.
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
Knoldus Inc.
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
Knoldus Inc.
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
Knoldus Inc.
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
Knoldus Inc.
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Knoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
Knoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
Knoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
Knoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
Knoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
Knoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
Knoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
Knoldus Inc.
 

More from Knoldus Inc. (20)

Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 

Recently uploaded

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 

Recently uploaded (20)

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 

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