SlideShare a Scribd company logo
1 of 44
Introduction to Typeclasses
2015-06-05 | Egemen Kalyoncu | Amsterdam
Agenda
● What is typeclass?
● Example
● Category Theory
● Example
● Higher Kinded Types
● Example
● Pros/Cons
Type Classes
“Typeclasses define a set of functions that can
have different implementations depending on the
type of data they are given” Real World Haskell
“In computer science, a type class is a type
system construct that supports ad-hoc
polymorphism.” Wikipedia
Type Classes
In Haskell, typeclass is the language
feature. Every class is a typeclass.
In Scala, typeclass is a pattern.
What isn’t Typeclass?
● It’s not only about FP. You can use it in OOP
as well.
● It’s not only about category theory.
Typeclass
Typeclass
● scala.math.Ordering
● scala.math.Numeric
● scalaz._
● spray.json._
Polymorphism
● Subtype polymorphism
● Parametric polymorphism (generics)
● Ad-hoc polymorphism (decoupling)
Serialization Example
class Ad(id: Int, title: String)
class User(id: Int, name: String)
Let’s implement serialization of these
classes.
Serialization Example (subtyping)
Serialization Example (subtyping)
trait Serializable { def serialize: String }
def doSerialize(in: Serializable)= in.serialize
class Ad extends Serializable {
def serialize: String = "serialized ad"
}
class User extends Serializable {
def serialize: String = "serialized user"
}
Serialization Example (typeclass)
trait Serializable[A] { def serialize(a: A): String }
def doSerialize[A](a: A, ser: Serializable[A]) =
ser.serialize(a)
Serialization Example (typeclass)
trait Serializable[A] { def serialize(a: A): String }
def doSerialize[A](a: A)(implicit ser: Serializable[A]) =
ser.serialize(a)
Serialization Example (typeclass)
object Serializable {
implicit val adSerializable: Serializable[Ad] =
new Serializable[Ad] {
def serialize(ad: Ad) = "serialized ad"
}
implicit val userSerializable: Serializable[User] =
new Serializable[User] {
def serialize(user: User) = "serialized user"
}
}
Serialization Example (typeclass)
scala> doSerialize(new Ad(1, "title1"))
res0: String = serialized ad
scala> doSerialize(new User(1, "user1"))
res1: String = serialized user
scala> doSerialize("bla")
<console>:11: error: could not find implicit value for parameter ser:
Serializable[String]
doSerialize("bla")
Category Theory
● Branch of mathematics
● Study of concepts(collection of objects)
and arrows(morphism)
● Functional design patterns in
programming
● Categories have properties and laws
● Categories can be types, cats, cars, …
Category Theory
arrow : function, map, morphism,
transformation, operator
Category Theory
trait Functor[F[_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
}
Category Theory
● Abstraction is useful but...
● Don’t forget social aspect of
programming
● Check if everybody is comfortable with
these advanced techniques.
How to sum
def sum(l: List[Int]): Int
How to sum
def sum(l: List[Int]): Int = l.reduce(_ + _)
How to sum
It looks like working. Except empty list.
How to sum
What about List[Double]?
How to sum
def sumDouble(l: List[Double]): Double = l.reduce(_ + _)
How to sum
def sumNumeric[A](l: List[A])(implicit A: Numeric[A]): A =
l.reduce(A.plus)
How to sum
What about List[String] or List[A]?
Let’s make it generic!
We need a typeclass to sum any type of A
How to sum
trait Addable[A] {
def plus(x: A, y: A): A
}
How to sum
object Addable {
implicit def numericAddable[A](implicit A: Numeric[A]): Addable[A] =
new Addable[A] {
def plus(x: A, y: A): A = A.plus(x, y)
}
implicit val stringAddable: Addable[String] =
new Addable[String] {
def plus(x: String, y: String): String = x + y
}
}
How to sum
def sumGeneric[A](l: List[A])(implicit A: Addable[A]): A =
l.reduce(A.plus)
How to sum
trait AddableWithZero[A] extends Addable[A] { def zero: A }
object AddableWithZero {
implicit def numericAddableZero[A](implicit A: Numeric[A]): AddableWithZero[A] =
new AddableWithZero[A] {
def plus(x: A, y: A): A = A.plus(x, y)
def zero: A = A.zero
}
implicit val stringAddableZero: AddableWithZero[String] =
new AddableWithZero[String] {
def plus(x: String, y: String): String = x + y
def zero: String = ""
}
}
How to sum
def sumGeneric[A](l: List[A])(implicit A: AddableWithZero[A]): A
= l.foldLeft(A.zero)(A.plus)
Semigroup and Monoid
● Abstract algebra
● Addable => Semigroup
● AddableWithZero => Monoid
Semigroup
trait Semigroup[A] {
def append(a: A, b: A): A
}
● Simple typeclass
● Law: Associativity
o append(a1, append(a2, a3) == append(append(a1, a2), a3)
Monoid
trait Monoid[A] extends Semigroup[A] {
def zero : A
}
● Identity element on top of semigroup
● Laws: Identity law
o zero append a == a
o a append zero == a
How to sum with Scalaz
import scalaz.Monoid
def sumGeneric[A](l: List[A])(implicit A: Monoid[A]): A =
l.foldLeft(A.zero)((x, y) => A.append(x, y))
Higher Kinded Types
● HKT gives us the ability to
generalize across type constructors
● Reduces code duplication
● parser combinators, DSL,
comprehensions are written using HKT
Higher Kinded Types
Higher Kinded Types
import scalaz.Monoid
def sumGeneric[A](l: List[A])(implicit A: Monoid[A]): A =
l.foldLeft(A.zero)((x, y) => A.append(x, y))
What if we want to sum over Vector, Tree or Map?
Higher Kinded Types
trait Foldable[F[_]] {
def fold[M](fa: F[M])(implicit M: Monoid[M]): M
}
object Foldable {
implicit val listFoldable: Foldable[List] =
new Foldable[List] {
def fold[M](fa: List[M])(implicit M: Monoid[M]): M =
fa.foldLeft(M.zero)((acc, elem) => M.append(acc, elem))
}
}
Higher Kinded Types
def sumGeneric2[F[_], A](fa: F[A])(implicit F: Foldable[F], A: Monoid[A]): A =
F.fold(fa)
Pros
● Unlike subtype polymorphism, type classes
work at compile time.
● Decouple functionality from types
● Extensible
Cons
● code complexity?
● performance penalty?
http://stackoverflow.com/questions/9327465/what-is-the-performance-impact-of-using-the-type-class-pattern-in-scala
References
● http://eed3si9n.com/learning-scalaz/polymorphism.html
● https://speakerdeck.com/marakana/ne-scala-2012-the-typeclass-pattern-an-alternative-to-inheritance
● http://typelevel.org/blog/2013/10/13/towards-scalaz-1.html
● http://typelevel.org/blog/2013/12/15/towards-scalaz-2.html
● https://www.haskell.org/tutorial/classes.html
● Scala in Depth
● Programming Scala 2nd Edition
● Generics of a Higher Kind - Adriaan Moors, Frank Piessens, and Martin Odersky

More Related Content

What's hot

Why functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersWhy functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersPiotr Paradziński
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into ScalaNehal Shah
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalazoxbow_lakes
 
Scala fun part: Reflection(runtime)
Scala fun part: Reflection(runtime)Scala fun part: Reflection(runtime)
Scala fun part: Reflection(runtime)vito jeng
 
Category Theory for Programmers
Category Theory for ProgrammersCategory Theory for Programmers
Category Theory for ProgrammersSantosh Rajan
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...Doris Chen
 
Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Alexander Podkhalyuzin
 
Category Theory for Mortal Programmers
Category Theory for Mortal ProgrammersCategory Theory for Mortal Programmers
Category Theory for Mortal ProgrammersStephan February
 
Extensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptExtensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptBrendan Eich
 
Ten-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala DevelopersTen-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala Developersihji
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
 

What's hot (20)

Cat's anatomy
Cat's anatomyCat's anatomy
Cat's anatomy
 
SacalaZa #1
SacalaZa #1SacalaZa #1
SacalaZa #1
 
Classroom Object Oriented Language (COOL)
Classroom Object Oriented Language (COOL)Classroom Object Oriented Language (COOL)
Classroom Object Oriented Language (COOL)
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Why functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersWhy functional programming and category theory strongly matters
Why functional programming and category theory strongly matters
 
07. haskell Membership
07. haskell Membership07. haskell Membership
07. haskell Membership
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
Cats in Scala
Cats in ScalaCats in Scala
Cats in Scala
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
Scala fun part: Reflection(runtime)
Scala fun part: Reflection(runtime)Scala fun part: Reflection(runtime)
Scala fun part: Reflection(runtime)
 
Category Theory for Programmers
Category Theory for ProgrammersCategory Theory for Programmers
Category Theory for Programmers
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
 
Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)Under the hood of scala implicits (kl10tch 10.03.2015)
Under the hood of scala implicits (kl10tch 10.03.2015)
 
Category Theory for Mortal Programmers
Category Theory for Mortal ProgrammersCategory Theory for Mortal Programmers
Category Theory for Mortal Programmers
 
Expresiones Regulares
Expresiones RegularesExpresiones Regulares
Expresiones Regulares
 
Extensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptExtensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScript
 
Ten-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala DevelopersTen-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala Developers
 
Scalaz
ScalazScalaz
Scalaz
 
06. haskell type builder
06. haskell type builder06. haskell type builder
06. haskell type builder
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
 

Viewers also liked

Java ee6 with scala
Java ee6 with scalaJava ee6 with scala
Java ee6 with scalaSatoshi Kubo
 
Why hadoop map reduce needs scala, an introduction to scoobi and scalding
Why hadoop map reduce needs scala, an introduction to scoobi and scaldingWhy hadoop map reduce needs scala, an introduction to scoobi and scalding
Why hadoop map reduce needs scala, an introduction to scoobi and scaldingXebia Nederland BV
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop seriesIntroducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop seriesHolden Karau
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in ScalaRose Toomey
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in ScalaPatrick Nicolas
 
Lightning fast genomics with Spark, Adam and Scala
Lightning fast genomics with Spark, Adam and ScalaLightning fast genomics with Spark, Adam and Scala
Lightning fast genomics with Spark, Adam and ScalaAndy Petrella
 
Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Evan Chan
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark Summit
 

Viewers also liked (13)

Java ee6 with scala
Java ee6 with scalaJava ee6 with scala
Java ee6 with scala
 
Why hadoop map reduce needs scala, an introduction to scoobi and scalding
Why hadoop map reduce needs scala, an introduction to scoobi and scaldingWhy hadoop map reduce needs scala, an introduction to scoobi and scalding
Why hadoop map reduce needs scala, an introduction to scoobi and scalding
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Annotations
AnnotationsAnnotations
Annotations
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop seriesIntroducing Apache Spark's Data Frames and Dataset APIs workshop series
Introducing Apache Spark's Data Frames and Dataset APIs workshop series
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in Scala
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in Scala
 
Lightning fast genomics with Spark, Adam and Scala
Lightning fast genomics with Spark, Adam and ScalaLightning fast genomics with Spark, Adam and Scala
Lightning fast genomics with Spark, Adam and Scala
 
Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015Akka in Production - ScalaDays 2015
Akka in Production - ScalaDays 2015
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin Odersky
 
Java Annotation
Java AnnotationJava Annotation
Java Annotation
 

Similar to Typeclasses

Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Scalac
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverseLuka Jacobowitz
 
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
 
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
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1Hang Zhao
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform ResearchVasil Remeniuk
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & ScalaMartin Ockajak
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and HaskellHermann Hueck
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersMiles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with SwiftFatih Nayebi, Ph.D.
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scalaakuklev
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsVasil Remeniuk
 
Introduction to programming with python
Introduction to programming with pythonIntroduction to programming with python
Introduction to programming with pythonPorimol Chandro
 
Motivation and Mechanics behind some aspects of Shapeless
Motivation and Mechanics behind some aspects of ShapelessMotivation and Mechanics behind some aspects of Shapeless
Motivation and Mechanics behind some aspects of ShapelessAnatolii Kmetiuk
 
Unified modeling language
Unified modeling languageUnified modeling language
Unified modeling languageamity2j
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in ScalaJorge Vásquez
 
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
 

Similar to Typeclasses (20)

Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
 
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
 
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)
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
 
Typeclass
TypeclassTypeclass
Typeclass
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with Swift
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami Patterns
 
Introduction to programming with python
Introduction to programming with pythonIntroduction to programming with python
Introduction to programming with python
 
Motivation and Mechanics behind some aspects of Shapeless
Motivation and Mechanics behind some aspects of ShapelessMotivation and Mechanics behind some aspects of Shapeless
Motivation and Mechanics behind some aspects of Shapeless
 
Unified modeling language
Unified modeling languageUnified modeling language
Unified modeling language
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in Scala
 
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
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 

Recently uploaded

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 

Recently uploaded (20)

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 

Typeclasses

  • 1. Introduction to Typeclasses 2015-06-05 | Egemen Kalyoncu | Amsterdam
  • 2. Agenda ● What is typeclass? ● Example ● Category Theory ● Example ● Higher Kinded Types ● Example ● Pros/Cons
  • 3. Type Classes “Typeclasses define a set of functions that can have different implementations depending on the type of data they are given” Real World Haskell “In computer science, a type class is a type system construct that supports ad-hoc polymorphism.” Wikipedia
  • 4. Type Classes In Haskell, typeclass is the language feature. Every class is a typeclass. In Scala, typeclass is a pattern.
  • 5. What isn’t Typeclass? ● It’s not only about FP. You can use it in OOP as well. ● It’s not only about category theory.
  • 8. Polymorphism ● Subtype polymorphism ● Parametric polymorphism (generics) ● Ad-hoc polymorphism (decoupling)
  • 9. Serialization Example class Ad(id: Int, title: String) class User(id: Int, name: String) Let’s implement serialization of these classes.
  • 11. Serialization Example (subtyping) trait Serializable { def serialize: String } def doSerialize(in: Serializable)= in.serialize class Ad extends Serializable { def serialize: String = "serialized ad" } class User extends Serializable { def serialize: String = "serialized user" }
  • 12. Serialization Example (typeclass) trait Serializable[A] { def serialize(a: A): String } def doSerialize[A](a: A, ser: Serializable[A]) = ser.serialize(a)
  • 13. Serialization Example (typeclass) trait Serializable[A] { def serialize(a: A): String } def doSerialize[A](a: A)(implicit ser: Serializable[A]) = ser.serialize(a)
  • 14. Serialization Example (typeclass) object Serializable { implicit val adSerializable: Serializable[Ad] = new Serializable[Ad] { def serialize(ad: Ad) = "serialized ad" } implicit val userSerializable: Serializable[User] = new Serializable[User] { def serialize(user: User) = "serialized user" } }
  • 15. Serialization Example (typeclass) scala> doSerialize(new Ad(1, "title1")) res0: String = serialized ad scala> doSerialize(new User(1, "user1")) res1: String = serialized user scala> doSerialize("bla") <console>:11: error: could not find implicit value for parameter ser: Serializable[String] doSerialize("bla")
  • 16. Category Theory ● Branch of mathematics ● Study of concepts(collection of objects) and arrows(morphism) ● Functional design patterns in programming ● Categories have properties and laws ● Categories can be types, cats, cars, …
  • 17. Category Theory arrow : function, map, morphism, transformation, operator
  • 18. Category Theory trait Functor[F[_]] { def map[A, B](fa: F[A])(f: A => B): F[B] }
  • 19. Category Theory ● Abstraction is useful but... ● Don’t forget social aspect of programming ● Check if everybody is comfortable with these advanced techniques.
  • 20. How to sum def sum(l: List[Int]): Int
  • 21. How to sum def sum(l: List[Int]): Int = l.reduce(_ + _)
  • 22. How to sum It looks like working. Except empty list.
  • 23. How to sum What about List[Double]?
  • 24. How to sum def sumDouble(l: List[Double]): Double = l.reduce(_ + _)
  • 25. How to sum def sumNumeric[A](l: List[A])(implicit A: Numeric[A]): A = l.reduce(A.plus)
  • 26. How to sum What about List[String] or List[A]?
  • 27. Let’s make it generic! We need a typeclass to sum any type of A
  • 28. How to sum trait Addable[A] { def plus(x: A, y: A): A }
  • 29. How to sum object Addable { implicit def numericAddable[A](implicit A: Numeric[A]): Addable[A] = new Addable[A] { def plus(x: A, y: A): A = A.plus(x, y) } implicit val stringAddable: Addable[String] = new Addable[String] { def plus(x: String, y: String): String = x + y } }
  • 30. How to sum def sumGeneric[A](l: List[A])(implicit A: Addable[A]): A = l.reduce(A.plus)
  • 31. How to sum trait AddableWithZero[A] extends Addable[A] { def zero: A } object AddableWithZero { implicit def numericAddableZero[A](implicit A: Numeric[A]): AddableWithZero[A] = new AddableWithZero[A] { def plus(x: A, y: A): A = A.plus(x, y) def zero: A = A.zero } implicit val stringAddableZero: AddableWithZero[String] = new AddableWithZero[String] { def plus(x: String, y: String): String = x + y def zero: String = "" } }
  • 32. How to sum def sumGeneric[A](l: List[A])(implicit A: AddableWithZero[A]): A = l.foldLeft(A.zero)(A.plus)
  • 33. Semigroup and Monoid ● Abstract algebra ● Addable => Semigroup ● AddableWithZero => Monoid
  • 34. Semigroup trait Semigroup[A] { def append(a: A, b: A): A } ● Simple typeclass ● Law: Associativity o append(a1, append(a2, a3) == append(append(a1, a2), a3)
  • 35. Monoid trait Monoid[A] extends Semigroup[A] { def zero : A } ● Identity element on top of semigroup ● Laws: Identity law o zero append a == a o a append zero == a
  • 36. How to sum with Scalaz import scalaz.Monoid def sumGeneric[A](l: List[A])(implicit A: Monoid[A]): A = l.foldLeft(A.zero)((x, y) => A.append(x, y))
  • 37. Higher Kinded Types ● HKT gives us the ability to generalize across type constructors ● Reduces code duplication ● parser combinators, DSL, comprehensions are written using HKT
  • 39. Higher Kinded Types import scalaz.Monoid def sumGeneric[A](l: List[A])(implicit A: Monoid[A]): A = l.foldLeft(A.zero)((x, y) => A.append(x, y)) What if we want to sum over Vector, Tree or Map?
  • 40. Higher Kinded Types trait Foldable[F[_]] { def fold[M](fa: F[M])(implicit M: Monoid[M]): M } object Foldable { implicit val listFoldable: Foldable[List] = new Foldable[List] { def fold[M](fa: List[M])(implicit M: Monoid[M]): M = fa.foldLeft(M.zero)((acc, elem) => M.append(acc, elem)) } }
  • 41. Higher Kinded Types def sumGeneric2[F[_], A](fa: F[A])(implicit F: Foldable[F], A: Monoid[A]): A = F.fold(fa)
  • 42. Pros ● Unlike subtype polymorphism, type classes work at compile time. ● Decouple functionality from types ● Extensible
  • 43. Cons ● code complexity? ● performance penalty? http://stackoverflow.com/questions/9327465/what-is-the-performance-impact-of-using-the-type-class-pattern-in-scala
  • 44. References ● http://eed3si9n.com/learning-scalaz/polymorphism.html ● https://speakerdeck.com/marakana/ne-scala-2012-the-typeclass-pattern-an-alternative-to-inheritance ● http://typelevel.org/blog/2013/10/13/towards-scalaz-1.html ● http://typelevel.org/blog/2013/12/15/towards-scalaz-2.html ● https://www.haskell.org/tutorial/classes.html ● Scala in Depth ● Programming Scala 2nd Edition ● Generics of a Higher Kind - Adriaan Moors, Frank Piessens, and Martin Odersky

Editor's Notes

  1. Abstract algebra