SlideShare a Scribd company logo
1 of 11
Download to read offline
Type classes
Dmytro Mitin
https://stepik.org/course/Introduction-to-programming-
with-dependent-types-in-Scala-2294/
March 2017
Dmytro Mitin Type classes
Inheritance in Java (implementing interface)
public interface Comparable<A> {
boolean cmp(A a1, A a2);
}
public class MyClass implements Comparable<MyClass> {
private int x;
@Override
public boolean cmp(MyClass a1, MyClass a2) {
return a1.x < a2.x;
}
}
public class OtherClass implements Comparable<OtherClass> {
private List<Integer> xs;
@Override
public boolean cmp(OtherClass a1, OtherClass a2) {
return a1.xs.get(0) < a2.xs.get(0);
}
}
Dmytro Mitin Type classes
Inheritance in Scala (extending trait)
trait Comparable[A] {
def cmp(a1: A, a2: A): Boolean
}
class MyClass(val x: Int) extends Comparable[MyClass] {
override def cmp(a1: MyClass, a2: MyClass): Boolean =
a1.x < a2.x
}
class OtherClass(val xs: List[Int]) extends Comparable[OtherClass] {
override def cmp(a1: OtherClass, a2: OtherClass): Boolean =
a1.xs.head < a2.xs.head
}
Dmytro Mitin Type classes
Type classes in Haskell
class Comparable a where
cmp :: a -> a -> Bool
instance Comparable Int where
cmp x y = x < y
instance Comparable a => Comparable [a] where
cmp xs ys = cmp (head xs) (head ys)
cmp (1 :: Int) 2
cmp [1 :: Int, 2] [2, 0]
> True
Dmytro Mitin Type classes
Implicits in Scala
Implicit parameters
def f(x: Int)(implicit y: String): String = x.toString + y
implicit val s: String = "abc"
f(10)
> 10abc
Implicit objects
class MyClass
def f(x: Int)(implicit y: MyClass): Int = x + y.hashCode
// implicit val obj = new MyClass
implicit object obj extends MyClass
f(10)
> ... /* some number */
Dmytro Mitin Type classes
Implicits in Scala
Implicit conversions
implicit def f(x: Int): String = x.toString + "abc"
def g(s: String): List[Char] = s.toList
g(123)
> List(1, 2, 3, a, b, c)
Implicit classes
implicit class MyClass(x: Int) {
def myMethod: Int = x + 1
}
123.myMethod
> 124
Dmytro Mitin Type classes
Type classes in Scala
trait Comparable[A] {
def cmp(a1: A, a2: A): Boolean
}
implicit object intComparable extends Comparable[Int] {
override def cmp(a1: Int, a2: Int): Boolean = a1 < a2
}
implicit class ComparableInt(x: Int) {
def cmp(y: Int): Boolean =
implicitly[Comparable[Int]].cmp(x, y)
}
Dmytro Mitin Type classes
Type classes in Scala
implicit def listComparable[A: Comparable]: Comparable[List[A]] =
new Comparable[List[A]] {
override def cmp(a1: List[A], a2: List[A]): Boolean =
implicitly[Comparable[A]].cmp(a1.head, a2.head)
}
// implicit def listComparable[A](implicit elementComparable:
// Comparable[A]): Comparable[List[A]] =
// new Comparable[List[A]] {
// override def cmp(a1: List[A], a2: List[A]): Boolean =
// elementComparable.cmp(a1.head, a2.head)
// }
// implicit def listComparable[A: Comparable]: Comparable[List[A]] =
// (a1: List[A], a2: List[A]) =>
// implicitly[Comparable[A]].cmp(a1.head, a2.head)
Dmytro Mitin Type classes
Type classes in Scala
implicit class ComparableList[A: Comparable](list: List[A]) {
def cmp(other: List[A]): Boolean =
implicitly[Comparable[List[A]]].cmp(list, other)
}
implicitly[Comparable[Int]].cmp(1, 2)
1.cmp(2)
1 cmp 2
implicitly[Comparable[List[Int]]].cmp(List(1, 2), List(2, 0))
List(1, 2).cmp(List(2, 0))
> true
Dmytro Mitin Type classes
Simulacrum library
build.sbt
libraryDependencies += "com.github.mpilquist" %%
"simulacrum" % "0.10.0"
addCompilerPlugin("org.scalameta" % "paradise" %
"3.0.0-beta4" cross CrossVersion.full)
import simulacrum.
@typeclass trait Comparable[A] {
@op("<<<") def cmp(a1: A, a2: A): Boolean
}
implicit object intComparable extends Comparable[Int] {
override def cmp(a1: Int, a2: Int): Boolean = a1 < a2
}
Dmytro Mitin Type classes
Simulacrum library
implicit def listComparable[A: Comparable]: Comparable[List[A]] =
new Comparable[List[A]] {
override def cmp(a1: List[A], a2: List[A]): Boolean =
implicitly[Comparable[A]].cmp(a1.head, a2.head)
}
import Comparable.ops.
1 <<< 2
List(1, 2) <<< List(2, 0)
> true
Dmytro Mitin Type classes

More Related Content

What's hot

Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoofelixtrepanier
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Type class survival guide
Type class survival guideType class survival guide
Type class survival guideMark Canlas
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idrisConor Farrell
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkAngelo Leto
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New GameJohn De Goes
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final TaglessJohn De Goes
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scalaRaymond Tay
 
Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceAlexey Raga
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 

What's hot (19)

Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoo
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
Type class survival guide
Type class survival guideType class survival guide
Type class survival guide
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idris
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with spark
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
 
SacalaZa #1
SacalaZa #1SacalaZa #1
SacalaZa #1
 
Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritance
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 

Viewers also liked

Type-level programming
Type-level programmingType-level programming
Type-level programmingDmytro Mitin
 
Scala dreaded underscore
Scala dreaded underscoreScala dreaded underscore
Scala dreaded underscoreRUDDER
 
Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由Yukishige Nakajo
 
Eliminators into dependent types
Eliminators into dependent typesEliminators into dependent types
Eliminators into dependent typesDmytro Mitin
 

Viewers also liked (6)

Type-level programming
Type-level programmingType-level programming
Type-level programming
 
Interpolation
InterpolationInterpolation
Interpolation
 
Scala dreaded underscore
Scala dreaded underscoreScala dreaded underscore
Scala dreaded underscore
 
Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由
 
Sigma type
Sigma typeSigma type
Sigma type
 
Eliminators into dependent types
Eliminators into dependent typesEliminators into dependent types
Eliminators into dependent types
 

Similar to Type classes

Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and HaskellHermann Hueck
 
05 - Scala. List type
05 - Scala. List type05 - Scala. List type
05 - Scala. List typeRoman Brovko
 
13 - Scala. Dependent pair type (Σ-type)
13 - Scala. Dependent pair type (Σ-type)13 - Scala. Dependent pair type (Σ-type)
13 - Scala. Dependent pair type (Σ-type)Roman Brovko
 
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
 
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
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalazoxbow_lakes
 
Inheritance And Traits
Inheritance And TraitsInheritance And Traits
Inheritance And TraitsPiyush Mishra
 
A brief introduction to apply functions
A brief introduction to apply functionsA brief introduction to apply functions
A brief introduction to apply functionsNIKET CHAURASIA
 
Introduction to programming with dependent types in Scala
Introduction to programming with dependent types in ScalaIntroduction to programming with dependent types in Scala
Introduction to programming with dependent types in ScalaDmytro Mitin
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scalaMichel Perez
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationEelco Visser
 
15 - Scala. Dependent function type (Π-type)
15 - Scala. Dependent function type (Π-type)15 - Scala. Dependent function type (Π-type)
15 - Scala. Dependent function type (Π-type)Roman Brovko
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda codePeter Lawrey
 

Similar to Type classes (20)

Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
05 - Scala. List type
05 - Scala. List type05 - Scala. List type
05 - Scala. List type
 
13 - Scala. Dependent pair type (Σ-type)
13 - Scala. Dependent pair type (Σ-type)13 - Scala. Dependent pair type (Σ-type)
13 - Scala. Dependent pair type (Σ-type)
 
Cats in Scala
Cats in ScalaCats in Scala
Cats in 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
 
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
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
Practical cats
Practical catsPractical cats
Practical cats
 
Inheritance And Traits
Inheritance And TraitsInheritance And Traits
Inheritance And Traits
 
A brief introduction to apply functions
A brief introduction to apply functionsA brief introduction to apply functions
A brief introduction to apply functions
 
Introduction to programming with dependent types in Scala
Introduction to programming with dependent types in ScalaIntroduction to programming with dependent types in Scala
Introduction to programming with dependent types in Scala
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scala
 
Data transformation-cheatsheet
Data transformation-cheatsheetData transformation-cheatsheet
Data transformation-cheatsheet
 
Introduction to-scala
Introduction to-scalaIntroduction to-scala
Introduction to-scala
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type Parameterization
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Built-in Classes in JAVA
Built-in Classes in JAVABuilt-in Classes in JAVA
Built-in Classes in JAVA
 
15 - Scala. Dependent function type (Π-type)
15 - Scala. Dependent function type (Π-type)15 - Scala. Dependent function type (Π-type)
15 - Scala. Dependent function type (Π-type)
 
Legacy lambda code
Legacy lambda codeLegacy lambda code
Legacy lambda code
 
Typeclasses
TypeclassesTypeclasses
Typeclasses
 

Recently uploaded

Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )aarthirajkumar25
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRDelhi Call girls
 
Formation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksFormation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksSérgio Sacani
 
Types of different blotting techniques.pptx
Types of different blotting techniques.pptxTypes of different blotting techniques.pptx
Types of different blotting techniques.pptxkhadijarafiq2012
 
Presentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxPresentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxgindu3009
 
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Sérgio Sacani
 
Cultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxCultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxpradhanghanshyam7136
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...RohitNehra6
 
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptxUnlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptxanandsmhk
 
Orientation, design and principles of polyhouse
Orientation, design and principles of polyhouseOrientation, design and principles of polyhouse
Orientation, design and principles of polyhousejana861314
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​kaibalyasahoo82800
 
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Lokesh Kothari
 
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...jana861314
 
Biological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfBiological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfmuntazimhurra
 
Isotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoIsotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoSérgio Sacani
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bSérgio Sacani
 
Work, Energy and Power for class 10 ICSE Physics
Work, Energy and Power for class 10 ICSE PhysicsWork, Energy and Power for class 10 ICSE Physics
Work, Energy and Power for class 10 ICSE Physicsvishikhakeshava1
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Nistarini College, Purulia (W.B) India
 

Recently uploaded (20)

Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
 
Formation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disksFormation of low mass protostars and their circumstellar disks
Formation of low mass protostars and their circumstellar disks
 
Types of different blotting techniques.pptx
Types of different blotting techniques.pptxTypes of different blotting techniques.pptx
Types of different blotting techniques.pptx
 
Presentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxPresentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptx
 
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
 
Cultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxCultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptx
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...
 
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptxUnlocking  the Potential: Deep dive into ocean of Ceramic Magnets.pptx
Unlocking the Potential: Deep dive into ocean of Ceramic Magnets.pptx
 
Orientation, design and principles of polyhouse
Orientation, design and principles of polyhouseOrientation, design and principles of polyhouse
Orientation, design and principles of polyhouse
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​
 
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
 
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
 
Biological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdfBiological Classification BioHack (3).pdf
Biological Classification BioHack (3).pdf
 
CELL -Structural and Functional unit of life.pdf
CELL -Structural and Functional unit of life.pdfCELL -Structural and Functional unit of life.pdf
CELL -Structural and Functional unit of life.pdf
 
Isotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoIsotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on Io
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
 
Work, Energy and Power for class 10 ICSE Physics
Work, Energy and Power for class 10 ICSE PhysicsWork, Energy and Power for class 10 ICSE Physics
Work, Energy and Power for class 10 ICSE Physics
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...
 

Type classes

  • 2. Inheritance in Java (implementing interface) public interface Comparable<A> { boolean cmp(A a1, A a2); } public class MyClass implements Comparable<MyClass> { private int x; @Override public boolean cmp(MyClass a1, MyClass a2) { return a1.x < a2.x; } } public class OtherClass implements Comparable<OtherClass> { private List<Integer> xs; @Override public boolean cmp(OtherClass a1, OtherClass a2) { return a1.xs.get(0) < a2.xs.get(0); } } Dmytro Mitin Type classes
  • 3. Inheritance in Scala (extending trait) trait Comparable[A] { def cmp(a1: A, a2: A): Boolean } class MyClass(val x: Int) extends Comparable[MyClass] { override def cmp(a1: MyClass, a2: MyClass): Boolean = a1.x < a2.x } class OtherClass(val xs: List[Int]) extends Comparable[OtherClass] { override def cmp(a1: OtherClass, a2: OtherClass): Boolean = a1.xs.head < a2.xs.head } Dmytro Mitin Type classes
  • 4. Type classes in Haskell class Comparable a where cmp :: a -> a -> Bool instance Comparable Int where cmp x y = x < y instance Comparable a => Comparable [a] where cmp xs ys = cmp (head xs) (head ys) cmp (1 :: Int) 2 cmp [1 :: Int, 2] [2, 0] > True Dmytro Mitin Type classes
  • 5. Implicits in Scala Implicit parameters def f(x: Int)(implicit y: String): String = x.toString + y implicit val s: String = "abc" f(10) > 10abc Implicit objects class MyClass def f(x: Int)(implicit y: MyClass): Int = x + y.hashCode // implicit val obj = new MyClass implicit object obj extends MyClass f(10) > ... /* some number */ Dmytro Mitin Type classes
  • 6. Implicits in Scala Implicit conversions implicit def f(x: Int): String = x.toString + "abc" def g(s: String): List[Char] = s.toList g(123) > List(1, 2, 3, a, b, c) Implicit classes implicit class MyClass(x: Int) { def myMethod: Int = x + 1 } 123.myMethod > 124 Dmytro Mitin Type classes
  • 7. Type classes in Scala trait Comparable[A] { def cmp(a1: A, a2: A): Boolean } implicit object intComparable extends Comparable[Int] { override def cmp(a1: Int, a2: Int): Boolean = a1 < a2 } implicit class ComparableInt(x: Int) { def cmp(y: Int): Boolean = implicitly[Comparable[Int]].cmp(x, y) } Dmytro Mitin Type classes
  • 8. Type classes in Scala implicit def listComparable[A: Comparable]: Comparable[List[A]] = new Comparable[List[A]] { override def cmp(a1: List[A], a2: List[A]): Boolean = implicitly[Comparable[A]].cmp(a1.head, a2.head) } // implicit def listComparable[A](implicit elementComparable: // Comparable[A]): Comparable[List[A]] = // new Comparable[List[A]] { // override def cmp(a1: List[A], a2: List[A]): Boolean = // elementComparable.cmp(a1.head, a2.head) // } // implicit def listComparable[A: Comparable]: Comparable[List[A]] = // (a1: List[A], a2: List[A]) => // implicitly[Comparable[A]].cmp(a1.head, a2.head) Dmytro Mitin Type classes
  • 9. Type classes in Scala implicit class ComparableList[A: Comparable](list: List[A]) { def cmp(other: List[A]): Boolean = implicitly[Comparable[List[A]]].cmp(list, other) } implicitly[Comparable[Int]].cmp(1, 2) 1.cmp(2) 1 cmp 2 implicitly[Comparable[List[Int]]].cmp(List(1, 2), List(2, 0)) List(1, 2).cmp(List(2, 0)) > true Dmytro Mitin Type classes
  • 10. Simulacrum library build.sbt libraryDependencies += "com.github.mpilquist" %% "simulacrum" % "0.10.0" addCompilerPlugin("org.scalameta" % "paradise" % "3.0.0-beta4" cross CrossVersion.full) import simulacrum. @typeclass trait Comparable[A] { @op("<<<") def cmp(a1: A, a2: A): Boolean } implicit object intComparable extends Comparable[Int] { override def cmp(a1: Int, a2: Int): Boolean = a1 < a2 } Dmytro Mitin Type classes
  • 11. Simulacrum library implicit def listComparable[A: Comparable]: Comparable[List[A]] = new Comparable[List[A]] { override def cmp(a1: List[A], a2: List[A]): Boolean = implicitly[Comparable[A]].cmp(a1.head, a2.head) } import Comparable.ops. 1 <<< 2 List(1, 2) <<< List(2, 0) > true Dmytro Mitin Type classes