SlideShare una empresa de Scribd logo
1 de 23
Descargar para leer sin conexión
Derek Chen-Becker




Pattern Matching in Scala

                    DOSUG IgNite Presentation
                          October 5th, 2010
I Believe You've Met Mr. “switch”...



switch(foo) {
case 1 : doBar("two"); break;
case 2 : doBar("one"); break;
default: doBar("forty-two");
}

      I can feel the excitement!
                                       2
Scala Merges OO and Functional Features




                                          3
Scala's “match” Like “switch”

    var foo : Int = 5
    foo match {
      case 1 => doBar("two")
      case 2 =>
        { doBar("one"); doBar("two") }
      case _ => doBar("lemon curry?")
    }
  No “break”. Each clause is self-contained
  Matches are tried in order, first match wins
  What in the heck is this “_” nonsense?
                                                 4
Match Against Broader Range of Types


 def literalMatch (in: Any) {
   in match {
     case 1 => doBar("One")
     case "test" => doBar("test")
     case 'x' => doBar("x")
     case 2.2f => doBar("float")
     case _ => doBar("lemon curry?")
   }
 }


  You can think of this like nested “if” statements

                                                      5
Alternate Patterns




 def literalMatch (in: Any) {
   in match {
     case 1 | 2 | 3 => doBar("One to three")
     case "this" | "that" => doBar("the other")
     case _ => doBar("lemon curry?")
   }
 }


  “|” allows clause to match multiple values

                                                  6
Binding Variables in Matches


 def literalMatch (in: Any) {
   in match {
     case n @ (1 | 2 | 3) => doBar("1-3:" + n)
     case t @ ("this" | "that") =>
       DoBar(t + " and the other")
     case x => doBar("We defaulted on " + x)
   }
 }



  You can bind a complex pattern with “x @ pattern”
  Just a variable as a pattern matches anything
                                                      7
Matching on Type



def typeMatch (in: Any) {
  in match {
    case i : Int => doBar("Int : " + i)
    case s : String => doBar(s)
    case _ => // NOOP
  }
}




                                          8
Matching on Generic Types


def typeMatch   (in: Any) {
  in match {
    case ls :   List[String] => doBar("danger!")
    case li :   List[Int] => doBar("never happens")
    case _ =>   // NOOP
  }
}



  You can't match on generic types because of erasure
  The compiler will warn about unchecked conversions if you
  do this
                                                              9
Guards Permit Fine-Grained Selection




                                       10
<Ahem> Guards Permit Fine-Grained Selection


def fifenator (in: Any) {
  in match {
    case i : Int if i > 12 && i < 47 => doBar("Int : " + i)
    case s : String if s.startsWith("DOSUG") => doBar(s)
    case _ => // NOOP
  }
}


  A guard is just a conditional clause for the match
  Because the type is being matched on the left, you have
  direct access to the type methods and fields without casts



                                                               11
A Brief Digression into Case Classes




case class Character(show : String, name : String)




  A Case Class is a special type of class that automatically
  adds methods for equals, hashcode, toString, and
  PATTERN MATCHING


                                                               12
A Brief Digression into Case Classes



def tvTime (c : Character) = c match {
  case Character(title, "Fred") =>
    doBar("Fred from " + title)
  case Character("Flintstones", n) => doBar(n)
  case c @ Character(_,_) => doBar(c.name)
}


  Constructor arguments automatically become properties that
  you can match against



                                                          13
But Wait, There's More!
                          Custom Extractors
                          Sealed class hierarchy
                          enforcement
                          Cleans Tough Stains!
                          Gentle on Hands!
                          Repels Cougars!
                          And more!




                                              14
Sealed Hierarchy Enforcement

sealed abstract class EntityType(val name : String)
case class Animal(n : String) extends EntityType(n)
case class Vegetable(n : String) extends EntityType(n)
case class Mineral(n : String) extends EntityType(n)

  “sealed” indicates that all direct subclasses are defined in
  the same source file
  Provides the compiler with a guaranteed bound on the type
  hierarchy:
          scala> def questionOne(t : EntityType) = t match {
             | case Animal(name) => println("Animal: " + name)
             | case Vegetable(name) => println("Veggie: " + name)
             |}
          <console>:8: warning: match is not exhaustive!
          missing combination      Mineral

              def questionOne(t : EntityType) = t match {           15
Custom Extraction Basics

object Something {
  def unapply(input : Foo) : Option[Bar] = {
    if (input.bar)
      Some(input.toBar)
    else
      None
  }
}
  An “object” is a singleton in the VM, defined as you would a
  class
  Methods on an object equivalent to “static” methods in Java




                                                             16
Custom Extraction Basics

object Something {
  def unapply(input : Foo) : Option[Bar] = {
    if (input.bar)
      Some(input.toBar)
    else
      None
  }
}
  Option is a predefined Scala type that has only two
  subclasses: Some and None
  A Some holds a typed value




                                                        17
Custom Extraction Basics

object Something {
  def unapply(input : Foo) : Option[Bar] = {
    if (input.bar)
      Some(input.toBar)
    else
      None
  }
}
  The “unapply” method holds special significance to the
  compiler
  Is used to attempt an extraction/match from a given input
  Returning Some(something) indicates a match
  Returning None indicates no match

                                                              18
Custom Extraction: IP Address

object Octet {
  def unapply(input : String) = try {
    val octet = input.toInt
    if (octet >= 0 && octet < 256)
      Some(octet)
    else
      None
  } catch {
    case _ => None
  }
}
  First we just define what an octet in an IP is:
     An Int...
     Between 0 and 255

                                                    19
Custom Extraction: IP Address


object IP {
def unapplySeq(input : String) : Option[Seq[Int]] =
  input.split('.') match {
    case Array(Octet(a), Octet(b), Octet(c), Octet(d)) =>
      Some(List(a,b,c,d))
    case _ => None
  }
}



  “unapplySeq” allows us to return a sequence of results on a
  match
  We nest our Octet matcher to match each IP component

                                                            20
Custom Extraction in Action
scala> def sumIP (address : String) = address match {
   | case IP(7, b, c, d) => println("Jackpot!"); Some(7 + b + c + d)
   | case IP(a,b,c,d) ⇒ Some(a + b + c + d)
   | case _ => None
   |}
sumIP: (address: String)Option[Int]

scala> sumIP("12.25.233.61")
res5: Option[Int] = Some(331)

scala> sumIP("12.25.233")
res6: Option[Int] = None

scala> sumIP("7.25.233.61")
Jackpot!
res7: Option[Int] = Some(326)
                                                                       21
Still With Me?




                 22
23

Más contenido relacionado

La actualidad más candente

Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In ScalaJoey Gibson
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Andrew Phillips
 
Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocolrocketcircus
 
Object Equality in Scala
Object Equality in ScalaObject Equality in Scala
Object Equality in ScalaKnoldus Inc.
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Bryan O'Sullivan
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Bryan O'Sullivan
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Bryan O'Sullivan
 
Understanding JavaScript
Understanding JavaScriptUnderstanding JavaScript
Understanding JavaScriptnodejsbcn
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Kel Cecil
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of AtrocityMichael Pirnat
 

La actualidad más candente (19)

Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In Scala
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 
Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocol
 
Grammarware Memes
Grammarware MemesGrammarware Memes
Grammarware Memes
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Object Equality in Scala
Object Equality in ScalaObject Equality in Scala
Object Equality in Scala
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2
 
Understanding JavaScript
Understanding JavaScriptUnderstanding JavaScript
Understanding JavaScript
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
Basic swift
Basic swiftBasic swift
Basic swift
 
Template Haskell
Template HaskellTemplate Haskell
Template Haskell
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 

Similar a Pattern Matching in Scala

Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scalaMichel Perez
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Crystal presentation in NY
Crystal presentation in NYCrystal presentation in NY
Crystal presentation in NYCrystal Language
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
Threequals - Case Equality in Ruby
Threequals - Case Equality in RubyThreequals - Case Equality in Ruby
Threequals - Case Equality in RubyLouis Scoras
 
Programming haskell chapter10
Programming haskell chapter10Programming haskell chapter10
Programming haskell chapter10Kousuke Ruichi
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in ScalaKnoldus Inc.
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 
Start Writing Groovy
Start Writing GroovyStart Writing Groovy
Start Writing GroovyEvgeny Goldin
 

Similar a Pattern Matching in Scala (20)

Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Crystal presentation in NY
Crystal presentation in NYCrystal presentation in NY
Crystal presentation in NY
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
Threequals - Case Equality in Ruby
Threequals - Case Equality in RubyThreequals - Case Equality in Ruby
Threequals - Case Equality in Ruby
 
Programming haskell chapter10
Programming haskell chapter10Programming haskell chapter10
Programming haskell chapter10
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
groovy & grails - lecture 3
groovy & grails - lecture 3groovy & grails - lecture 3
groovy & grails - lecture 3
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
Start Writing Groovy
Start Writing GroovyStart Writing Groovy
Start Writing Groovy
 

Último

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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 Takeoffsammart93
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
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 FMESafe Software
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
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
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Pattern Matching in Scala

  • 1. Derek Chen-Becker Pattern Matching in Scala DOSUG IgNite Presentation October 5th, 2010
  • 2. I Believe You've Met Mr. “switch”... switch(foo) { case 1 : doBar("two"); break; case 2 : doBar("one"); break; default: doBar("forty-two"); } I can feel the excitement! 2
  • 3. Scala Merges OO and Functional Features 3
  • 4. Scala's “match” Like “switch” var foo : Int = 5 foo match { case 1 => doBar("two") case 2 => { doBar("one"); doBar("two") } case _ => doBar("lemon curry?") } No “break”. Each clause is self-contained Matches are tried in order, first match wins What in the heck is this “_” nonsense? 4
  • 5. Match Against Broader Range of Types def literalMatch (in: Any) { in match { case 1 => doBar("One") case "test" => doBar("test") case 'x' => doBar("x") case 2.2f => doBar("float") case _ => doBar("lemon curry?") } } You can think of this like nested “if” statements 5
  • 6. Alternate Patterns def literalMatch (in: Any) { in match { case 1 | 2 | 3 => doBar("One to three") case "this" | "that" => doBar("the other") case _ => doBar("lemon curry?") } } “|” allows clause to match multiple values 6
  • 7. Binding Variables in Matches def literalMatch (in: Any) { in match { case n @ (1 | 2 | 3) => doBar("1-3:" + n) case t @ ("this" | "that") => DoBar(t + " and the other") case x => doBar("We defaulted on " + x) } } You can bind a complex pattern with “x @ pattern” Just a variable as a pattern matches anything 7
  • 8. Matching on Type def typeMatch (in: Any) { in match { case i : Int => doBar("Int : " + i) case s : String => doBar(s) case _ => // NOOP } } 8
  • 9. Matching on Generic Types def typeMatch (in: Any) { in match { case ls : List[String] => doBar("danger!") case li : List[Int] => doBar("never happens") case _ => // NOOP } } You can't match on generic types because of erasure The compiler will warn about unchecked conversions if you do this 9
  • 11. <Ahem> Guards Permit Fine-Grained Selection def fifenator (in: Any) { in match { case i : Int if i > 12 && i < 47 => doBar("Int : " + i) case s : String if s.startsWith("DOSUG") => doBar(s) case _ => // NOOP } } A guard is just a conditional clause for the match Because the type is being matched on the left, you have direct access to the type methods and fields without casts 11
  • 12. A Brief Digression into Case Classes case class Character(show : String, name : String) A Case Class is a special type of class that automatically adds methods for equals, hashcode, toString, and PATTERN MATCHING 12
  • 13. A Brief Digression into Case Classes def tvTime (c : Character) = c match { case Character(title, "Fred") => doBar("Fred from " + title) case Character("Flintstones", n) => doBar(n) case c @ Character(_,_) => doBar(c.name) } Constructor arguments automatically become properties that you can match against 13
  • 14. But Wait, There's More! Custom Extractors Sealed class hierarchy enforcement Cleans Tough Stains! Gentle on Hands! Repels Cougars! And more! 14
  • 15. Sealed Hierarchy Enforcement sealed abstract class EntityType(val name : String) case class Animal(n : String) extends EntityType(n) case class Vegetable(n : String) extends EntityType(n) case class Mineral(n : String) extends EntityType(n) “sealed” indicates that all direct subclasses are defined in the same source file Provides the compiler with a guaranteed bound on the type hierarchy: scala> def questionOne(t : EntityType) = t match { | case Animal(name) => println("Animal: " + name) | case Vegetable(name) => println("Veggie: " + name) |} <console>:8: warning: match is not exhaustive! missing combination Mineral def questionOne(t : EntityType) = t match { 15
  • 16. Custom Extraction Basics object Something { def unapply(input : Foo) : Option[Bar] = { if (input.bar) Some(input.toBar) else None } } An “object” is a singleton in the VM, defined as you would a class Methods on an object equivalent to “static” methods in Java 16
  • 17. Custom Extraction Basics object Something { def unapply(input : Foo) : Option[Bar] = { if (input.bar) Some(input.toBar) else None } } Option is a predefined Scala type that has only two subclasses: Some and None A Some holds a typed value 17
  • 18. Custom Extraction Basics object Something { def unapply(input : Foo) : Option[Bar] = { if (input.bar) Some(input.toBar) else None } } The “unapply” method holds special significance to the compiler Is used to attempt an extraction/match from a given input Returning Some(something) indicates a match Returning None indicates no match 18
  • 19. Custom Extraction: IP Address object Octet { def unapply(input : String) = try { val octet = input.toInt if (octet >= 0 && octet < 256) Some(octet) else None } catch { case _ => None } } First we just define what an octet in an IP is: An Int... Between 0 and 255 19
  • 20. Custom Extraction: IP Address object IP { def unapplySeq(input : String) : Option[Seq[Int]] = input.split('.') match { case Array(Octet(a), Octet(b), Octet(c), Octet(d)) => Some(List(a,b,c,d)) case _ => None } } “unapplySeq” allows us to return a sequence of results on a match We nest our Octet matcher to match each IP component 20
  • 21. Custom Extraction in Action scala> def sumIP (address : String) = address match { | case IP(7, b, c, d) => println("Jackpot!"); Some(7 + b + c + d) | case IP(a,b,c,d) ⇒ Some(a + b + c + d) | case _ => None |} sumIP: (address: String)Option[Int] scala> sumIP("12.25.233.61") res5: Option[Int] = Some(331) scala> sumIP("12.25.233") res6: Option[Int] = None scala> sumIP("7.25.233.61") Jackpot! res7: Option[Int] = Some(326) 21
  • 23. 23