SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados (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
 

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

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

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

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

Último

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
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
 
"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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
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
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
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
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Último (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"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...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
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)
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
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
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 

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