SlideShare una empresa de Scribd logo
1 de 45
Descargar para leer sin conexión
Type Classes


Wealthfront Engineering
Type Class


Type system construct that supports ad-hoc
 polymorphism, achieved by adding constraints
 to type variables in parametrically
 polymorphic types
Type Class


Type system construct that supports ad-hoc
 polymorphism, achieved by adding constraints
 to type variables in parametrically
 polymorphic types
Type Class


Type system construct that supports ad-hoc
 polymorphism, achieved by adding constraints
 to type variables in parametrically
 polymorphic types
Type Class


Type system construct that supports ad-hoc
 polymorphism, achieved by adding constraints
 to type variables in parametrically
 polymorphic types
Type Class


Type system construct that supports ad-hoc
 polymorphism, achieved by adding constraints
 to type variables in parametrically
 polymorphic types
pol•y•mor•phism            ¦ päli môr fizəm¦



nounthe occurrence of something in several
  different forms	
  




                    New Oxford American Dictionary
In particular:


Polymorphism is a programming language
  feature that allows values of different data
  types to be handled using a uniform interface
Several Types of Polymorphism


•    Ad-hoc polymorphism
•    Inclusion polymorphism
•    Parametric polymorphism
•    Bounded parametric polymorphism
Several Types of Polymorphism


•  Ad-hoc polymorphism
  –  Operator and method overloading
•  Inclusion polymorphism
•  Parametric polymorphism
•  Bounded parametric polymorphism
Several Types of Polymorphism


•  Ad-hoc polymorphism
•  Inclusion polymorphism
  –  Subtyping
•  Parametric polymorphism
•  Bounded parametric polymorphism
Several Types of Polymorphism


•  Ad-hoc polymorphism
•  Inclusion polymorphism
•  Parametric polymorphism
  –  Generics
•  Bounded parametric polymorphism
Several Types of Polymorphism


•    Ad-hoc polymorphism
•    Inclusion polymorphism
•    Parametric polymorphism
•    Bounded parametric polymorphism
     –  Generics with bounded wildcards
Ad-hoc polymorphism


Control moving through one named function is
 dispatched to various other functions without
 having to specify the exact function being
 called
Ad-hoc polymorphism


String greet() {
   return "Hello, World!";
}
Ad-hoc polymorphism


String greet(String name) {
   return "Hello," + name + "!";
}
Ad-hoc polymorphism


String greet(int count) {
   return "Hello, World" + repeat("!", count);
}
Ad-hoc polymorphism


>   greet();
    Hello, World!
>   greet("Wealthfront");
    Hello, Wealthfront!
>   greet(3);
    Hello, World!!!
Parametric polymorphism


A function or a data type can be written
  generically so that it can handle values
  identically without depending on their type
Parametric polymorphism


size :: a . [a] → int
size [] = 0
size (x:xs) = 1 + size xs
Parametric polymorphism


>   size [1, 2]
    2
>   size ["hello", "hi", "yo"]
    3
Bounded parametric polymorphism


A function or a data type require some
  knowledge of its data types but can otherwise
  work parametrically
Bounded parametric polymorphism



<T extends Comparable<T>> List<T> sort(List<T> list) {
   return …
}
Type Class


Type system construct that supports ad-hoc
 polymorphism, achieved by adding constraints
 to type variables in parametrically
 polymorphic types
Type Class


Type system construct that supports ad-hoc
 polymorphism, achieved by adding constraints
 to type variables in parametrically
 polymorphic types
Type Class


Type system construct that supports ad-hoc
 polymorphism, achieved by adding constraints
 to type variables in parametrically
 polymorphic types
Type Class


Type system construct that supports ad-hoc
 polymorphism, achieved by adding constraints
 to type variables in parametrically
 polymorphic types
Type Class Eq


class Eq a where
 eq :: a → a → bool
 ne :: a → a → bool
Implementation for int


instance Eq int where
 eq m n = m == n
 ne m n = m != n
Implementation for Instrument


instance Eq Instrument where
 eq x {id = xid} y {id = yid} = xid == yid
 ne x {id = xid} y {id = yid} = xid != yid
Usage


member :: (Eq a) ⇒ a → [a] → bool
member y [] = false
member y (x:xs) = (eq x y) || member y xs
Ad-hoc polymorphism


member :: (Eq a) ⇒ a → [a] → bool
member y [] = false
member y (x:xs) = (eq x y) || member y xs
Parametric polymorphism


member :: (Eq a) ⇒ a → [a] → bool
member y [] = false
member y (x:xs) = (eq x y) || member y xs
Constraint on type variable


member :: (Eq a) ⇒ a → [a] → bool
member y [] = false
member y (x:xs) = (eq x y) || member y xs
Type Classes vs. Interfaces?
Similar, yet different:
•  Implementation is separate
•  Subtyping is not entailed
•  Static dispatch (ad-hoc polymorphism) vs.
   dynamic single dispatch
Return type-based dispatch


foo :: (Parseable a) ⇒ a → String → a
foo x s = x + parse s
Return type-based dispatch


>   foo "Hello, " "World!"
    Hello, World!
>   foo 2 "3"
    5
Return type-based dispatch
class String implements Parseable {
   String parse() {
      return this;
   }
   int parse() {
      return Integer.parseInt(this);
   }
}
Type Class in Scala


trait Parseable[T] {
   def parse(s: String): T
}
Implementation in Scala for Int


implicit object ParseableInt extends Parseable[Int] {
   def parse(s: String) = Integer.parseInt(s)
}
Usage in Scala


def foo[T: Parseable](t: T, s: String): T = 
  t + implicitly[Parseable[T]].parse(s)
Usage in Scala


>   foo("Hello, ", "World!");
    Hello, World! : String
>   foo(2, "3");
    5 : Int
Usage in Scala


def foo[T: Parseable](s: String): T = 
  implicitly[Parseable[T]].parse(s)
Usage in Scala


>   "Hello, " + foo("World!");
    Hello, World! : String
>   2 + foo("3");
    5 : Int
>   foo[Int]("3");
    3 : Int
The End




FYI, Monad is a Type Class.

Más contenido relacionado

La actualidad más candente

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
Skills Matter
 

La actualidad más candente (19)

Object Oriented Programming_Lecture 2
Object Oriented Programming_Lecture 2Object Oriented Programming_Lecture 2
Object Oriented Programming_Lecture 2
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
From android/java to swift (1)
From android/java to swift (1)From android/java to swift (1)
From android/java to swift (1)
 
Introduction to type classes in Scala
Introduction to type classes in ScalaIntroduction to type classes in Scala
Introduction to type classes in Scala
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 
Scala Type Classes: Basics and More
Scala Type Classes:  Basics and MoreScala Type Classes:  Basics and More
Scala Type Classes: Basics and More
 
‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
 
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
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Classy Monad Transformers (Stop Eff'ing Around)
Classy Monad Transformers (Stop Eff'ing Around)Classy Monad Transformers (Stop Eff'ing Around)
Classy Monad Transformers (Stop Eff'ing Around)
 
What are Sealed Classes in Scala?
What are Sealed Classes in Scala?What are Sealed Classes in Scala?
What are Sealed Classes in Scala?
 
Type Systems
Type SystemsType Systems
Type Systems
 
5variables in c#
5variables in c#5variables in c#
5variables in c#
 
Java
JavaJava
Java
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
 
Generics In and Out
Generics In and OutGenerics In and Out
Generics In and Out
 
Vhdl identifiers,data types
Vhdl identifiers,data typesVhdl identifiers,data types
Vhdl identifiers,data types
 
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
 

Similar a Type Classes

Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: Polymorphism
Eelco Visser
 
What's next in Julia
What's next in JuliaWhat's next in Julia
What's next in Julia
Jiahao Chen
 

Similar a Type Classes (20)

Ti1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: PolymorphismTi1220 Lecture 7: Polymorphism
Ti1220 Lecture 7: Polymorphism
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Functional programming with F#
Functional programming with F#Functional programming with F#
Functional programming with F#
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Milano JS Meetup - Gabriele Petronella - Codemotion Milan 2016
Milano JS Meetup -  Gabriele Petronella - Codemotion Milan 2016Milano JS Meetup -  Gabriele Petronella - Codemotion Milan 2016
Milano JS Meetup - Gabriele Petronella - Codemotion Milan 2016
 
Strong typing : adoption, adaptation and organisation
Strong typing : adoption, adaptation and organisationStrong typing : adoption, adaptation and organisation
Strong typing : adoption, adaptation and organisation
 
Fire in the type hole
Fire in the type holeFire in the type hole
Fire in the type hole
 
Type Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLikeType Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLike
 
Xtend Programming Language
Xtend Programming LanguageXtend Programming Language
Xtend Programming Language
 
What's next in Julia
What's next in JuliaWhat's next in Julia
What's next in Julia
 
Cats in Scala
Cats in ScalaCats in Scala
Cats in Scala
 
Strong typing @ php leeds
Strong typing  @ php leedsStrong typing  @ php leeds
Strong typing @ php leeds
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
 
Scala: A brief tutorial
Scala: A brief tutorialScala: A brief tutorial
Scala: A brief tutorial
 
Declare Your Language: Name Resolution
Declare Your Language: Name ResolutionDeclare Your Language: Name Resolution
Declare Your Language: Name Resolution
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Let's make a contract: The art of designing a Java API | DevNation Tech Talk
Let's make a contract: The art of designing a Java API | DevNation Tech TalkLet's make a contract: The art of designing a Java API | DevNation Tech Talk
Let's make a contract: The art of designing a Java API | DevNation Tech Talk
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Type Classes

  • 2. Type Class Type system construct that supports ad-hoc polymorphism, achieved by adding constraints to type variables in parametrically polymorphic types
  • 3. Type Class Type system construct that supports ad-hoc polymorphism, achieved by adding constraints to type variables in parametrically polymorphic types
  • 4. Type Class Type system construct that supports ad-hoc polymorphism, achieved by adding constraints to type variables in parametrically polymorphic types
  • 5. Type Class Type system construct that supports ad-hoc polymorphism, achieved by adding constraints to type variables in parametrically polymorphic types
  • 6. Type Class Type system construct that supports ad-hoc polymorphism, achieved by adding constraints to type variables in parametrically polymorphic types
  • 7. pol•y•mor•phism ¦ päli môr fizəm¦ nounthe occurrence of something in several different forms   New Oxford American Dictionary
  • 8. In particular: Polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface
  • 9. Several Types of Polymorphism •  Ad-hoc polymorphism •  Inclusion polymorphism •  Parametric polymorphism •  Bounded parametric polymorphism
  • 10. Several Types of Polymorphism •  Ad-hoc polymorphism –  Operator and method overloading •  Inclusion polymorphism •  Parametric polymorphism •  Bounded parametric polymorphism
  • 11. Several Types of Polymorphism •  Ad-hoc polymorphism •  Inclusion polymorphism –  Subtyping •  Parametric polymorphism •  Bounded parametric polymorphism
  • 12. Several Types of Polymorphism •  Ad-hoc polymorphism •  Inclusion polymorphism •  Parametric polymorphism –  Generics •  Bounded parametric polymorphism
  • 13. Several Types of Polymorphism •  Ad-hoc polymorphism •  Inclusion polymorphism •  Parametric polymorphism •  Bounded parametric polymorphism –  Generics with bounded wildcards
  • 14. Ad-hoc polymorphism Control moving through one named function is dispatched to various other functions without having to specify the exact function being called
  • 15. Ad-hoc polymorphism String greet() { return "Hello, World!"; }
  • 16. Ad-hoc polymorphism String greet(String name) { return "Hello," + name + "!"; }
  • 17. Ad-hoc polymorphism String greet(int count) { return "Hello, World" + repeat("!", count); }
  • 18. Ad-hoc polymorphism > greet(); Hello, World! > greet("Wealthfront"); Hello, Wealthfront! > greet(3); Hello, World!!!
  • 19. Parametric polymorphism A function or a data type can be written generically so that it can handle values identically without depending on their type
  • 20. Parametric polymorphism size :: a . [a] → int size [] = 0 size (x:xs) = 1 + size xs
  • 21. Parametric polymorphism > size [1, 2] 2 > size ["hello", "hi", "yo"] 3
  • 22. Bounded parametric polymorphism A function or a data type require some knowledge of its data types but can otherwise work parametrically
  • 23. Bounded parametric polymorphism <T extends Comparable<T>> List<T> sort(List<T> list) { return … }
  • 24. Type Class Type system construct that supports ad-hoc polymorphism, achieved by adding constraints to type variables in parametrically polymorphic types
  • 25. Type Class Type system construct that supports ad-hoc polymorphism, achieved by adding constraints to type variables in parametrically polymorphic types
  • 26. Type Class Type system construct that supports ad-hoc polymorphism, achieved by adding constraints to type variables in parametrically polymorphic types
  • 27. Type Class Type system construct that supports ad-hoc polymorphism, achieved by adding constraints to type variables in parametrically polymorphic types
  • 28. Type Class Eq class Eq a where eq :: a → a → bool ne :: a → a → bool
  • 29. Implementation for int instance Eq int where eq m n = m == n ne m n = m != n
  • 30. Implementation for Instrument instance Eq Instrument where eq x {id = xid} y {id = yid} = xid == yid ne x {id = xid} y {id = yid} = xid != yid
  • 31. Usage member :: (Eq a) ⇒ a → [a] → bool member y [] = false member y (x:xs) = (eq x y) || member y xs
  • 32. Ad-hoc polymorphism member :: (Eq a) ⇒ a → [a] → bool member y [] = false member y (x:xs) = (eq x y) || member y xs
  • 33. Parametric polymorphism member :: (Eq a) ⇒ a → [a] → bool member y [] = false member y (x:xs) = (eq x y) || member y xs
  • 34. Constraint on type variable member :: (Eq a) ⇒ a → [a] → bool member y [] = false member y (x:xs) = (eq x y) || member y xs
  • 35. Type Classes vs. Interfaces? Similar, yet different: •  Implementation is separate •  Subtyping is not entailed •  Static dispatch (ad-hoc polymorphism) vs. dynamic single dispatch
  • 36. Return type-based dispatch foo :: (Parseable a) ⇒ a → String → a foo x s = x + parse s
  • 37. Return type-based dispatch > foo "Hello, " "World!" Hello, World! > foo 2 "3" 5
  • 38. Return type-based dispatch class String implements Parseable { String parse() { return this; } int parse() { return Integer.parseInt(this); } }
  • 39. Type Class in Scala trait Parseable[T] { def parse(s: String): T }
  • 40. Implementation in Scala for Int implicit object ParseableInt extends Parseable[Int] { def parse(s: String) = Integer.parseInt(s) }
  • 41. Usage in Scala def foo[T: Parseable](t: T, s: String): T = t + implicitly[Parseable[T]].parse(s)
  • 42. Usage in Scala > foo("Hello, ", "World!"); Hello, World! : String > foo(2, "3"); 5 : Int
  • 43. Usage in Scala def foo[T: Parseable](s: String): T = implicitly[Parseable[T]].parse(s)
  • 44. Usage in Scala > "Hello, " + foo("World!"); Hello, World! : String > 2 + foo("3"); 5 : Int > foo[Int]("3"); 3 : Int
  • 45. The End FYI, Monad is a Type Class.