SlideShare une entreprise Scribd logo
1  sur  27
Prabhat Kashyap
Sr. Software Consultant
Knoldus Inc.
Cats in Scala
Presented By: Prabhat Kashyap
Sr. Software Consultant
Agenda
 Introduction
 Type class
 Monoids and Semigroups
 Functors
 Monads
 Monad Transformers
Introduction
Cats is a library which provides abstractions for functional
programming in the Scala programming language.
The name is a playful shortening of the word category.
-Documentation
Type Class
The Type Class
 Type classes were first introduced in Haskell as a new approach to ad-hoc polymorphism.
 Type classes in Haskell are based on Hindley–Milner type system.
 Scala's type inference is based on Local Type Inference.
object Math {
trait NumberLike[A] {
def add(a: A, b: A): A
def subtract(a: A, b: A): A
def multiply(a: A, b: A): A
def divide(a: A, b: A): A
}
}
Type Class Instances
 The instances of a type class provide implementations for the types.
 Members of type classes are usually singleton objects.
 implicit keyword before each of the type class implementations.
Type Class Instances [Example]
object Math {
trait NumberLike[A] {
def add(a: A, b: A): A
def subtract(a: A, b: A): A
def multiply(a: A, b: A): A
def divide(a: A, b: A): A
}
implicit val intLike: NumberLike[Int] = new
NumberLike[Int] {
override def add(a: Int, b: Int): Int = a + b
override def subtract(a: Int, b: Int): Int = a - b
override def multiply(a: Int, b: Int): Int = a * b
override def divide(a: Int, b: Int): Int = a / b
}
}
Type Class Interfaces
 A type class interface is any functionality we expose to users.
object DoTheMath{
import Math.NumberLike
def addition[A](a: A, b: A)(implicit ev: NumberLike[A]) =
ev.add(a, b)
}
DoTheMath.addition(1,2)
Type class in Cats
 Cats is written using a modular structure.
 It allows us to choose which type classes, instances, and interface methods we want to use.
import cats.Show
import cats.instances.int._
val showInt: Show[Int] = Show.apply[Int]
val intToString: String = showInt.show(1)
import cats.syntax.show._
123.show
Defining Custom Instances
import java.util.Date
implicit val dateShow: Show[Date] =
Show.show(date => s"${date.getTime}ms since the epoch.")
dateShow.show(new Date())
Result:
res2: String = 1532873812098ms since the epoch.
trait Monoid[A] {
def combine(x: A, y: A): A
def empty: A
}
A monoid for a type A is:
 an operation on combine with type (A, A) => A
 an element empty of type A
 Must follow associative law.
 Must follow identity law.
Monoids
Monoids [Few Example]
// Example Addition
1 + 1 = 2
1 + 0 = 1 & 0 + 1 = 1
1 + (1 + 2) = 4
(1 + 1) + 2 = 4
 Integer Addition
 Integer Multiplication
 String Concatatination
// Example Concatenation
“1” + “1” = “11”
“1” + “” = “1” & “” + “1” = “1”
“1” + (“1” + “2”) = “112”
(“1” + “1”) + “2” = “112”
// Example Subtraction
(4 – 2) – 2 = 0
4 – (2 – 2) = 4
Semigroup
trait Semigroup[A] {
def combine(x: A, y: A): A
}
 A semigroup is just the combine part of a monoid
 For example NonEmptyList or Positive Integer
trait Monoid[A] extends Semigroup[A] {
def empty: A
}
Monoids and Semigroup in Cats
Type Class
 The monoid type class is cats.kernel.Monoid , which is aliased as cats.Monoid.
 Monoid extends cats.kernel.Semigroup , which is aliased as cats.Semigroup.
Instance
import cats.Monoid
import cats.instances.string._
Monoid[String].combine("Hello ", " World")
Monoids and Semigroup in Cats
Syntax
●Cats provides syntax for the combine method (|+| operator).
import cats.instances.option._
import cats.syntax.semigroup._
val result = Option(1) |+| Monoid[Option[Int]].empty
Result = Option(1)
Functors
 A Functor is anything with a map method.
 For example: Option , List , and Either
 Functor as used to transforming the values inside. For example:
Option(1).map(_ + 1) // Option(2)
Result = Option(2)
Functors in Cats
Type Class
●The funtor type class is cats.Functor.
import cats.Functor
Functor[Option].map(Option(1))(_ + 2)
Instance
import cats.Functor
import cats.instances.option._
val optionIncrementFunc = Functor[Option].lift((x:Int) => x + 1)
val result = optionIncrementFunc(Option(2))
Functors in Cats
Syntax
●The funtor type class is cats.syntax.functor
Monads
 Monads are one of the most common abstractions in Scala.
 A monad is anything with a constructor and a flatMap method.
 All functors are monads.
A monad is a mechanism for sequencing computations.
Isn’t the functors are same as monads?
Monads Definition
trait Monad[F[_]] {
def pure[A](value: A): F[A]
def flatMap[A, B](value: F[A])(func: A => F[B]): F[B]
}
Monads in Cats
Type Class
The monad type class is cats.Monad.
import cats.Monad
Monad[Option].pure(3)
Instance
import cats.Monad
import cats.instances.option._
Monad[Option].flatMap(Option(3))(a => Some(a + 2))
// Option[Int] = Some(5)
Monads in Cats
Syntax
●cats.syntax.flatMap provides syntax for flatMap
●cats.syntax.functor provides syntax for map
●cats.syntax.applicative provides syntax for pure
Monads Transformation
 Monad transformation in standard Scala library is difficult and messy.
 Nested for-comprehension.
for {
optUser <- listOfUser
} yield {
for {
user <- optUser
} yield user.name
}
Cat Transformers
 Cats provides transformers for many monads, each named with a T suffix.
 EitherT composes Either with other monads, OptionT composes Option , and so on.
 Each monad transformer is a data type, defined in cats.data.
cats.data.OptionT
cats.data.EitherT
cats.data.ReaderT
cats.data.WriterT
cats.data.StateT
cats.data.IdT
Reference
Any queriesor Feedback?
Email @ prabhat.kashyap@knoldus.in
Cats in Scala

Contenu connexe

Tendances (20)

Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
JSpiders - Wrapper classes
JSpiders - Wrapper classesJSpiders - Wrapper classes
JSpiders - Wrapper classes
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
 
Python oop class 1
Python oop   class 1Python oop   class 1
Python oop class 1
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector class
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
.NET F# Class constructor
.NET F# Class constructor.NET F# Class constructor
.NET F# Class constructor
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 

Similaire à Cats in Scala

Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and HaskellHermann Hueck
 
Bestiary of Functional Programming with Cats
Bestiary of Functional Programming with CatsBestiary of Functional Programming with Cats
Bestiary of Functional Programming with Cats💡 Tomasz Kogut
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaVasil Remeniuk
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskellJongsoo Lee
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Alexander Podkhalyuzin
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Monads and friends demystified
Monads and friends demystifiedMonads and friends demystified
Monads and friends demystifiedAlessandro Lacava
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsPhilip Schwarz
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
 
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
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & ScalaMartin Ockajak
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 

Similaire à Cats in Scala (20)

Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
Practical cats
Practical catsPractical cats
Practical cats
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Scala: A brief tutorial
Scala: A brief tutorialScala: A brief tutorial
Scala: A brief tutorial
 
Bestiary of Functional Programming with Cats
Bestiary of Functional Programming with CatsBestiary of Functional Programming with Cats
Bestiary of Functional Programming with Cats
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius Valatka
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Monads and friends demystified
Monads and friends demystifiedMonads and friends demystified
Monads and friends demystified
 
C# programming
C# programming C# programming
C# programming
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and Cats
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
Typeclasses
TypeclassesTypeclasses
Typeclasses
 
09. haskell Context
09. haskell Context09. haskell Context
09. haskell Context
 
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
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 

Plus de Knoldus Inc.

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxKnoldus 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 ParsingKnoldus 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 IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus 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.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus 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 TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus 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.
 

Plus de Knoldus Inc. (20)

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
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
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
 

Dernier

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Dernier (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Cats in Scala

  • 1. Prabhat Kashyap Sr. Software Consultant Knoldus Inc. Cats in Scala Presented By: Prabhat Kashyap Sr. Software Consultant
  • 2. Agenda  Introduction  Type class  Monoids and Semigroups  Functors  Monads  Monad Transformers
  • 3. Introduction Cats is a library which provides abstractions for functional programming in the Scala programming language. The name is a playful shortening of the word category. -Documentation
  • 5. The Type Class  Type classes were first introduced in Haskell as a new approach to ad-hoc polymorphism.  Type classes in Haskell are based on Hindley–Milner type system.  Scala's type inference is based on Local Type Inference. object Math { trait NumberLike[A] { def add(a: A, b: A): A def subtract(a: A, b: A): A def multiply(a: A, b: A): A def divide(a: A, b: A): A } }
  • 6. Type Class Instances  The instances of a type class provide implementations for the types.  Members of type classes are usually singleton objects.  implicit keyword before each of the type class implementations.
  • 7. Type Class Instances [Example] object Math { trait NumberLike[A] { def add(a: A, b: A): A def subtract(a: A, b: A): A def multiply(a: A, b: A): A def divide(a: A, b: A): A } implicit val intLike: NumberLike[Int] = new NumberLike[Int] { override def add(a: Int, b: Int): Int = a + b override def subtract(a: Int, b: Int): Int = a - b override def multiply(a: Int, b: Int): Int = a * b override def divide(a: Int, b: Int): Int = a / b } }
  • 8. Type Class Interfaces  A type class interface is any functionality we expose to users. object DoTheMath{ import Math.NumberLike def addition[A](a: A, b: A)(implicit ev: NumberLike[A]) = ev.add(a, b) } DoTheMath.addition(1,2)
  • 9. Type class in Cats  Cats is written using a modular structure.  It allows us to choose which type classes, instances, and interface methods we want to use. import cats.Show import cats.instances.int._ val showInt: Show[Int] = Show.apply[Int] val intToString: String = showInt.show(1) import cats.syntax.show._ 123.show
  • 10. Defining Custom Instances import java.util.Date implicit val dateShow: Show[Date] = Show.show(date => s"${date.getTime}ms since the epoch.") dateShow.show(new Date()) Result: res2: String = 1532873812098ms since the epoch.
  • 11. trait Monoid[A] { def combine(x: A, y: A): A def empty: A } A monoid for a type A is:  an operation on combine with type (A, A) => A  an element empty of type A  Must follow associative law.  Must follow identity law. Monoids
  • 12. Monoids [Few Example] // Example Addition 1 + 1 = 2 1 + 0 = 1 & 0 + 1 = 1 1 + (1 + 2) = 4 (1 + 1) + 2 = 4  Integer Addition  Integer Multiplication  String Concatatination // Example Concatenation “1” + “1” = “11” “1” + “” = “1” & “” + “1” = “1” “1” + (“1” + “2”) = “112” (“1” + “1”) + “2” = “112” // Example Subtraction (4 – 2) – 2 = 0 4 – (2 – 2) = 4
  • 13. Semigroup trait Semigroup[A] { def combine(x: A, y: A): A }  A semigroup is just the combine part of a monoid  For example NonEmptyList or Positive Integer trait Monoid[A] extends Semigroup[A] { def empty: A }
  • 14. Monoids and Semigroup in Cats Type Class  The monoid type class is cats.kernel.Monoid , which is aliased as cats.Monoid.  Monoid extends cats.kernel.Semigroup , which is aliased as cats.Semigroup. Instance import cats.Monoid import cats.instances.string._ Monoid[String].combine("Hello ", " World")
  • 15. Monoids and Semigroup in Cats Syntax ●Cats provides syntax for the combine method (|+| operator). import cats.instances.option._ import cats.syntax.semigroup._ val result = Option(1) |+| Monoid[Option[Int]].empty Result = Option(1)
  • 16. Functors  A Functor is anything with a map method.  For example: Option , List , and Either  Functor as used to transforming the values inside. For example: Option(1).map(_ + 1) // Option(2) Result = Option(2)
  • 17. Functors in Cats Type Class ●The funtor type class is cats.Functor. import cats.Functor Functor[Option].map(Option(1))(_ + 2) Instance import cats.Functor import cats.instances.option._ val optionIncrementFunc = Functor[Option].lift((x:Int) => x + 1) val result = optionIncrementFunc(Option(2))
  • 18. Functors in Cats Syntax ●The funtor type class is cats.syntax.functor
  • 19. Monads  Monads are one of the most common abstractions in Scala.  A monad is anything with a constructor and a flatMap method.  All functors are monads. A monad is a mechanism for sequencing computations. Isn’t the functors are same as monads?
  • 20. Monads Definition trait Monad[F[_]] { def pure[A](value: A): F[A] def flatMap[A, B](value: F[A])(func: A => F[B]): F[B] }
  • 21. Monads in Cats Type Class The monad type class is cats.Monad. import cats.Monad Monad[Option].pure(3) Instance import cats.Monad import cats.instances.option._ Monad[Option].flatMap(Option(3))(a => Some(a + 2)) // Option[Int] = Some(5)
  • 22. Monads in Cats Syntax ●cats.syntax.flatMap provides syntax for flatMap ●cats.syntax.functor provides syntax for map ●cats.syntax.applicative provides syntax for pure
  • 23. Monads Transformation  Monad transformation in standard Scala library is difficult and messy.  Nested for-comprehension. for { optUser <- listOfUser } yield { for { user <- optUser } yield user.name }
  • 24. Cat Transformers  Cats provides transformers for many monads, each named with a T suffix.  EitherT composes Either with other monads, OptionT composes Option , and so on.  Each monad transformer is a data type, defined in cats.data. cats.data.OptionT cats.data.EitherT cats.data.ReaderT cats.data.WriterT cats.data.StateT cats.data.IdT
  • 26. Any queriesor Feedback? Email @ prabhat.kashyap@knoldus.in