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

GenAI talk for Young at Wageningen University & Research (WUR) March 2024
GenAI talk for Young at Wageningen University & Research (WUR) March 2024GenAI talk for Young at Wageningen University & Research (WUR) March 2024
GenAI talk for Young at Wageningen University & Research (WUR) March 2024Jene van der Heide
 
Four Spheres of the Earth Presentation.ppt
Four Spheres of the Earth Presentation.pptFour Spheres of the Earth Presentation.ppt
Four Spheres of the Earth Presentation.pptJoemSTuliba
 
OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024innovationoecd
 
Introduction of Human Body & Structure of cell.pptx
Introduction of Human Body & Structure of cell.pptxIntroduction of Human Body & Structure of cell.pptx
Introduction of Human Body & Structure of cell.pptxMedical College
 
Organic farming with special reference to vermiculture
Organic farming with special reference to vermicultureOrganic farming with special reference to vermiculture
Organic farming with special reference to vermicultureTakeleZike1
 
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdfPests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdfPirithiRaju
 
User Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather StationUser Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather StationColumbia Weather Systems
 
User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)Columbia Weather Systems
 
Servosystem Theory / Cybernetic Theory by Petrovic
Servosystem Theory / Cybernetic Theory by PetrovicServosystem Theory / Cybernetic Theory by Petrovic
Servosystem Theory / Cybernetic Theory by PetrovicAditi Jain
 
The dark energy paradox leads to a new structure of spacetime.pptx
The dark energy paradox leads to a new structure of spacetime.pptxThe dark energy paradox leads to a new structure of spacetime.pptx
The dark energy paradox leads to a new structure of spacetime.pptxEran Akiva Sinbar
 
Observational constraints on mergers creating magnetism in massive stars
Observational constraints on mergers creating magnetism in massive starsObservational constraints on mergers creating magnetism in massive stars
Observational constraints on mergers creating magnetism in massive starsSérgio Sacani
 
PROJECTILE MOTION-Horizontal and Vertical
PROJECTILE MOTION-Horizontal and VerticalPROJECTILE MOTION-Horizontal and Vertical
PROJECTILE MOTION-Horizontal and VerticalMAESTRELLAMesa2
 
Citronella presentation SlideShare mani upadhyay
Citronella presentation SlideShare mani upadhyayCitronella presentation SlideShare mani upadhyay
Citronella presentation SlideShare mani upadhyayupadhyaymani499
 
REVISTA DE BIOLOGIA E CIÊNCIAS DA TERRA ISSN 1519-5228 - Artigo_Bioterra_V24_...
REVISTA DE BIOLOGIA E CIÊNCIAS DA TERRA ISSN 1519-5228 - Artigo_Bioterra_V24_...REVISTA DE BIOLOGIA E CIÊNCIAS DA TERRA ISSN 1519-5228 - Artigo_Bioterra_V24_...
REVISTA DE BIOLOGIA E CIÊNCIAS DA TERRA ISSN 1519-5228 - Artigo_Bioterra_V24_...Universidade Federal de Sergipe - UFS
 
《Queensland毕业文凭-昆士兰大学毕业证成绩单》
《Queensland毕业文凭-昆士兰大学毕业证成绩单》《Queensland毕业文凭-昆士兰大学毕业证成绩单》
《Queensland毕业文凭-昆士兰大学毕业证成绩单》rnrncn29
 
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubai
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In DubaiDubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubai
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubaikojalkojal131
 
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingBase editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingNetHelix
 

Recently uploaded (20)

GenAI talk for Young at Wageningen University & Research (WUR) March 2024
GenAI talk for Young at Wageningen University & Research (WUR) March 2024GenAI talk for Young at Wageningen University & Research (WUR) March 2024
GenAI talk for Young at Wageningen University & Research (WUR) March 2024
 
Four Spheres of the Earth Presentation.ppt
Four Spheres of the Earth Presentation.pptFour Spheres of the Earth Presentation.ppt
Four Spheres of the Earth Presentation.ppt
 
AZOTOBACTER AS BIOFERILIZER.PPTX
AZOTOBACTER AS BIOFERILIZER.PPTXAZOTOBACTER AS BIOFERILIZER.PPTX
AZOTOBACTER AS BIOFERILIZER.PPTX
 
OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024
 
Introduction of Human Body & Structure of cell.pptx
Introduction of Human Body & Structure of cell.pptxIntroduction of Human Body & Structure of cell.pptx
Introduction of Human Body & Structure of cell.pptx
 
Organic farming with special reference to vermiculture
Organic farming with special reference to vermicultureOrganic farming with special reference to vermiculture
Organic farming with special reference to vermiculture
 
Let’s Say Someone Did Drop the Bomb. Then What?
Let’s Say Someone Did Drop the Bomb. Then What?Let’s Say Someone Did Drop the Bomb. Then What?
Let’s Say Someone Did Drop the Bomb. Then What?
 
PLASMODIUM. PPTX
PLASMODIUM. PPTXPLASMODIUM. PPTX
PLASMODIUM. PPTX
 
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdfPests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdf
 
User Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather StationUser Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather Station
 
User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)
 
Servosystem Theory / Cybernetic Theory by Petrovic
Servosystem Theory / Cybernetic Theory by PetrovicServosystem Theory / Cybernetic Theory by Petrovic
Servosystem Theory / Cybernetic Theory by Petrovic
 
The dark energy paradox leads to a new structure of spacetime.pptx
The dark energy paradox leads to a new structure of spacetime.pptxThe dark energy paradox leads to a new structure of spacetime.pptx
The dark energy paradox leads to a new structure of spacetime.pptx
 
Observational constraints on mergers creating magnetism in massive stars
Observational constraints on mergers creating magnetism in massive starsObservational constraints on mergers creating magnetism in massive stars
Observational constraints on mergers creating magnetism in massive stars
 
PROJECTILE MOTION-Horizontal and Vertical
PROJECTILE MOTION-Horizontal and VerticalPROJECTILE MOTION-Horizontal and Vertical
PROJECTILE MOTION-Horizontal and Vertical
 
Citronella presentation SlideShare mani upadhyay
Citronella presentation SlideShare mani upadhyayCitronella presentation SlideShare mani upadhyay
Citronella presentation SlideShare mani upadhyay
 
REVISTA DE BIOLOGIA E CIÊNCIAS DA TERRA ISSN 1519-5228 - Artigo_Bioterra_V24_...
REVISTA DE BIOLOGIA E CIÊNCIAS DA TERRA ISSN 1519-5228 - Artigo_Bioterra_V24_...REVISTA DE BIOLOGIA E CIÊNCIAS DA TERRA ISSN 1519-5228 - Artigo_Bioterra_V24_...
REVISTA DE BIOLOGIA E CIÊNCIAS DA TERRA ISSN 1519-5228 - Artigo_Bioterra_V24_...
 
《Queensland毕业文凭-昆士兰大学毕业证成绩单》
《Queensland毕业文凭-昆士兰大学毕业证成绩单》《Queensland毕业文凭-昆士兰大学毕业证成绩单》
《Queensland毕业文凭-昆士兰大学毕业证成绩单》
 
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubai
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In DubaiDubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubai
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubai
 
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingBase editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
 

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