SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Taking your side effects aside
Taking your side effects asideTaking your side effects aside
Taking your side effects aside💡 Tomasz Kogut
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
non-strict functions, bottom and scala by-name parameters
non-strict functions, bottom and scala by-name parametersnon-strict functions, bottom and scala by-name parameters
non-strict functions, bottom and scala by-name parametersPhilip Schwarz
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
Java 9 Module System Introduction
Java 9 Module System IntroductionJava 9 Module System Introduction
Java 9 Module System IntroductionDan Stine
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in ScalaHermann Hueck
 
Capabilities for Resources and Effects
Capabilities for Resources and EffectsCapabilities for Resources and Effects
Capabilities for Resources and EffectsMartin Odersky
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldPhilip Schwarz
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
Hibernate
HibernateHibernate
HibernateAjay K
 
Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0Jorge Vásquez
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practicesfelixbillon
 
The Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingThe Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingJosé Paumard
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scaladatamantra
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the WildJosé Paumard
 

Tendances (20)

Taking your side effects aside
Taking your side effects asideTaking your side effects aside
Taking your side effects aside
 
SOLID _Principles.pptx
SOLID _Principles.pptxSOLID _Principles.pptx
SOLID _Principles.pptx
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
non-strict functions, bottom and scala by-name parameters
non-strict functions, bottom and scala by-name parametersnon-strict functions, bottom and scala by-name parameters
non-strict functions, bottom and scala by-name parameters
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Java 9 Module System Introduction
Java 9 Module System IntroductionJava 9 Module System Introduction
Java 9 Module System Introduction
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
Capabilities for Resources and Effects
Capabilities for Resources and EffectsCapabilities for Resources and Effects
Capabilities for Resources and Effects
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
 
Pbo
PboPbo
Pbo
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java modules
Java modulesJava modules
Java modules
 
Hibernate
HibernateHibernate
Hibernate
 
Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
The Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern MatchingThe Future of Java: Records, Sealed Classes and Pattern Matching
The Future of Java: Records, Sealed Classes and Pattern Matching
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 

Similaire à Scala categorytheory

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
 
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 mattersPiotr Paradziński
 
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 CatsPhilip Schwarz
 
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 worldDebasish 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. MonadsKirill Kozlov
 
Category Theory in 10 Minutes
Category Theory in 10 MinutesCategory Theory in 10 Minutes
Category Theory in 10 MinutesJordan Parmer
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginnerskenbot
 
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 LanguagesWim 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.pptxZawarali786
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture TwoAngelo Corsaro
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersChris
 
Function notation by sadiq
Function notation by sadiqFunction notation by sadiq
Function notation by sadiqSadiq Hussain
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharpDaniele Pozzobon
 

Similaire à Scala categorytheory (20)

Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
 
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...
 
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
 
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
 
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 in 10 Minutes
Category Theory in 10 MinutesCategory Theory in 10 Minutes
Category Theory in 10 Minutes
 
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
 

Plus de Knoldus Inc.

Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxKnoldus Inc.
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinKnoldus Inc.
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks PresentationKnoldus Inc.
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Knoldus Inc.
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxKnoldus Inc.
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance TestingKnoldus Inc.
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxKnoldus Inc.
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationKnoldus Inc.
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.Knoldus Inc.
 

Plus de Knoldus Inc. (20)

Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptx
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and Kotlin
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks Presentation
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptx
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance Testing
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptx
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower Presentation
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.
 

Dernier

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 

Dernier (20)

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 

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