SlideShare uma empresa Scribd logo
1 de 25
SCALA
PATTERN MATCHING, CONCEPTS AND
IMPLEMENTATIONS
Mustapha Michrafy PhD
M. MICHRAFY & C. VALLIEZ
Contact the authors :
datascience.km@gmail.com
datascience.km@gmail.com1
Cyril Valliez PhD
- We thank Oussama Lachiri for helpful discussions.
Context
This study was presented at the seminar
« Data Science Principales, Tools and
Applications » at Cermsem laboratory
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com2
Goal
This study aims to present the pattern
matching and its implementation with
Scala
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com3
Prerequisite
Knowledge of
• Scala programming language
• Functional programming notion
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com4
Agenda
1. Basic pattern matching
2. Pattern matching and for loop
3. Pattern alternative: operator « | »
4. Pattern guards
5. Pattern guards and logical operator OR
6. Pattern matching and recursive function
7. Pattern matching on type
8. Pattern matching on tuple
9. Pattern matching on Option
10. Pattern matching on Immutable Collection
11. Pattern matching on Immutable Map
12. Pattern matching on Immutable Set
13. Pattern matching on List
14. Pattern matching on case class
15. Nested Pattern Matching in Case Classes
16. Matching on regular expression
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com5
Basic pattern matching : switch-case
def getChoicegetChoicegetChoicegetChoice(choicechoicechoicechoice: Int): String = choicechoicechoicechoice matchmatchmatchmatch {
case 0 => "no"
case 1 => "yes"
case ____ => "error"
}
if choice = 0 then "no"
else if choice = 1 then "yes"
else then "error"
Pattern matching
getChoice(1) //> res0: String = yes
getChoice(0) //> res1: String = no
getChoice(3) //> res2: String = error
Testing
The wildcard pattern “_”
matches any object whatsoever.
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com6
Pattern matching and initialization
val choicechoicechoicechoice = 0
var mesg ==== choicechoicechoicechoice match {
case 0 => "no"
case 1 => "yes"
case _ => "error"
}
println(mesg) //> no
We can use pattern matching for initializing a variable.
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com7
Pattern matching and for loop
val choiceschoiceschoiceschoices = List(0,1,10)
for( choicechoicechoicechoice <- choices) {
choice match {
case 0 => println("no")
case 1 => println("yes")
case _ => println("error")
}
}
//> no
//> yes
//>error
We can use pattern matching with for loop
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com8
Pattern alternative: operator « | »
def getChoicegetChoicegetChoicegetChoice(choicechoicechoicechoice: Int): String = choicechoicechoicechoice matchmatchmatchmatch {
casecasecasecase 0000 =>=>=>=> """"no"no"no"no"
casecasecasecase 1111 => "no"=> "no"=> "no"=> "no"
case 2 => "yes"
case ____ => "error"
}
if choice in {0,1} then "no"
else if choice = 2 then "oui"
else then "error"
Pattern matching
« | » : OR
With “|” , we can have multiple tests on a single line
def getChoicegetChoicegetChoicegetChoice(choicechoicechoicechoice: Int): String = choicechoicechoicechoice matchmatchmatchmatch {
casecasecasecase 0000 | 1 =>| 1 =>| 1 =>| 1 => """"no"no"no"no"
case 2 => "yes"
case ____ => "error"
}
getChoice(0) //>res1: String = no
getChoice(1) //>res2: String = no
Testing
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com9
Pattern guards
def sign(x:Double) : Byte = x match {
case x if x < 0if x < 0if x < 0if x < 0 => -1
case x if x > 0if x > 0if x > 0if x > 0 => 1
case _ => 0
}
-1 if x < 0
sing(x) = 1 if x > 0
0 sinon
Pattern matching
sign(0) //> res1: Byte = 0
sign(2) //> res2: Byte = 1
sign(-2) //> res3: Byte = -1
Testing
A pattern guard comes after a
pattern and starts with an if.
If a pattern guard is present, the
match succeeds only if the
guard evaluates to true
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com10
Pattern guards and logical operator OR
def OR(p:Boolean, q: Boolean) : Boolean = (p, q)(p, q)(p, q)(p, q) match {
case (x, y) if x==true | y==trueif x==true | y==trueif x==true | y==trueif x==true | y==true => true
case _ => false
}
OR(false, false) //> res1: Boolean = false
OR(false, true) //> res2: Boolean = true
p q p OR q
T T T
T F T
F T T
F F F
If (p=T | q=T) then OR(p,q)=true
else OR(p,q) =false
Testing
Pattern matching
Transform multiple parameters into one tuple (p,q)
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com11
1
1
Pattern matching and recursive function
1 if n = 0
n*(n-1)! otherwise
n! ====
def factorialfactorialfactorialfactorial(n: Int): Int = n match {
case 0 => 1
case _ => n*factorialfactorialfactorialfactorial(n-1)
}
def factorialfactorialfactorialfactorial(n:Int) : Int = {
def fcfcfcfc(n:Int, p:Int) : Int = ((((n,pn,pn,pn,p)))) match {
case (0,c) => c
case (m,c) => fc(m-1,p*m)
}
fcfcfcfc(n,1)
}
factorial(0) //> res 1: Int = 1
factorial(4) //> res 2: Int = 24
1 Using a tuple (n,p)
2 Initialize an accumulator p to 1
Tail-recursive function
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com12
Pattern matching on type
def matchByTypematchByTypematchByTypematchByType(z: Any): String = z match {
case b:Boolean => s"A boolean : $b"
case d:Double => s"A double : $d"
case _ => " Unknown type "
}
1
2
3
1 If z is Boolean type, b takes its value.
2 If z is the type Double , d takes its value.
3 Use wildcard when z is neither a Boolean type nor a Double type
A typed pattern x:T consists of a pattern variable x and a type pattern T.
The type of x is the type pattern T, where each type variable and wildcard
is replaced by a fresh, unknown type.
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com13
Pattern matching on tuple
def detectZeroInTupledetectZeroInTupledetectZeroInTupledetectZeroInTuple(x: Tuple2[Any,Any]):String = x match {
case (0,0|(0,0)) => "Both values zero."
case (0,b) => s"First value is 0 in (0,$b)"
case (a, 0) => s"Second value is 0 in ($a, 0)"
case _ => "Both nonzero : " + x
}
1
The tuple pattern matches input in tuple form and enables the tuple to be
decomposed into its constituent elements by using pattern matching
variables for each position in the tuple.
detectZeroInTuple((0,(0,0))) //> res1: String = Both values zero.
detectZeroInTuple((0,0)) //> res2: String = Both values zero.
detectZeroInTuple((0,11)) //> res3: String = First value is 0 in (0,11)
1 Match a first pattern if x=(0,0) or x=(0,(0,0)).
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com14
Pattern matching on Option
def getValueOptiongetValueOptiongetValueOptiongetValueOption[Any](x:Option[Any]) : String = x match{
case Some(x) => s"Some $x"
case None => "None "
}
1
Option -sealed abstract class- represents optional values.
Instances of Option are either an instance of SomeSomeSomeSome or the
object None.None.None.None.
getValueOption(Option("hello")) //> Some hello
getValueOption(Option(null)) //> None
getValueOption(Option(())) //> Some ()
getValueOption(Option(List(10,11))) //Some List(10, 11))
1 Match a Some(x) if x represents an existing value.
Option
Some None
c
c o
2 Match a None if x represents a non-existing value.
2
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com15
Pattern matching on immutable collection
import scala.collection.immutable._
def getTypegetTypegetTypegetType(x:Traversable[Any]) : String = x match{
case s:Set[Any] => s"A Immutable Set : $s"
case q:Seq[Any] => s"A Immutable Seq : $q"
case _ => "A Immutable Map : $x"
}
getType(Set(0,2,4)) //> A Immutable Set : Set(0, 2, 4)
getType(1 to 3) //> Immutable Seq : Range(1, 2, 3)
getType(HashMap[Int,Int](1->13)) //> A Immutable Map : Map(1 -> 13)
2 Match a pattern then the type of x is returned
Iterable
Set
Map
Seq
t
t
t
t
traversable
t
1
1
2
3
3 Match wildcard then type map is returned
This hierarchy is valid for mutable and immutable collections
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com16
Pattern matching on Immutable Map
import scala.collection.immutable._
def getTypeOfMapgetTypeOfMapgetTypeOfMapgetTypeOfMap(x:Map[Int,Int]) : String = x match{
case _:HashMap[Int,Int] => "A HashMap "
case _:TreeMap[Int,Int] => "A TreeMap "
case _ => "A ListMap "
}
getTypeOfMap(HashMap[Int,Int](1->12,2->10)) //>A HashMap
getTypeOfMap(TreeMap[Int,Int](1->3,6->6)) //> A TreeMap
getTypeOfMap(ListMap[Int,Int](1->13,6->16)) //> A ListMap
1 if x is neither a HashMap nor a TreeMap then x is a ListMap
Map
HashMap
ListMap
TreeMap
t
c
c
c
This hierarchy is valid only for the immutable Map
Map is a Trait and all (children) are implementation
classes
1
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com17
Pattern matching on immutable Set
import scala.collection.immutable._
import scala.collection.immutable.BitSet._
def getTypeOfSetgetTypeOfSetgetTypeOfSetgetTypeOfSet(x:Set[Int]) : String = x match{
case h:HashSet[Int] => "A HashSet " + (h.size,h.sum)
case t:TreeSet[Int] => "A TreeSet " + (t.size,t.sum)
case l:ListSet[Int] => "A ListSet " + (l.size,l.sum)
case z:AnyRef => "type : " + z.getClass.getName
}
getTypeOfSet(new BitSet1(10)) //> type : scala.collection.immutable.BitSet$BitSet1
getTypeOfSet(HashSet(1,10,12)) //> A HashSet (3,23)
getTypeOfSet(TreeSet(1,10)) //> A TreeSet (2,11)
getTypeOfSet(ListSet(1,11,12)) //> A ListSet (3,24)
Set
HashSet
ListSet
BitSet
t
c
c
c
This hierarchy is valid only for the immutable Set.
The Set is a Trait. BitSet is an abstract class and all children are
the class.
TreeSet
c
SortedSet
t
The subclasses of the abstract class BitSet are BitSet1, BitSet2 and BitSetN
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com18
Pattern matching on List 1/2
def sizeListsizeListsizeListsizeList[A](ls : List[A]) : Int = ls match{
case Nil => 0
case _::q => sizeList(q) + 1
}
The following function computes the length of a list.
It is based on two constructors NilNilNilNil and “::”.
sizeList(List()) //> res40: Int = 0
sizeList(List(1)) //> res41: Int = 1
sizeList(List(1,(1,2),3,4)) //> res42: Int = 4
1 If the list is empty, Nil, then we return 0.
2 If ls represents a no-empty list then the length of list is
(1+length(q)), where q represents the tail of the list.
1
2
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com19
Pattern matching on List 2/2
def identifyListeidentifyListeidentifyListeidentifyListe(ls: List[Any]): String = ls match {
case Nil => "empty list"
case _::Nil => "list with single element"
case _::_::Nil => "list has two elements"
case _ => "list has at least tree elements"
}
All lists are built from two constructors : NilNilNilNil and “::”....
NilNilNilNil represents a empty list
:::::::: builds a non empty list characterized by a head and a tail.
identifyListe(Nil) //> empty list
identifyListe(List((1,2))) //> list with single element
identifyListe(List("Scala", 3)) //> list has two elements
identifyListe(List(1,2,3)) //> list has at least tree elements
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com20
Pattern matching on case class
case class PersonPersonPersonPerson(name: String, age: Int)
def validateAgevalidateAgevalidateAgevalidateAge(p: Person): Option[String] = p match {
case Person(name, age) if age > 18 => Some(s"Hi $name! age $age")
case _ => None
}
Case classes are classes that get to String, hashCode, and equals methods
automatically. It provide a recursive decomposition mechanism via pattern
matching
validateAge(Person("Alice", 19)) //> Some(Hi Alice! age 19)
validateAge(Person("Bill", 15)) //> None
2 If the age is greater than18 , then we return the name and age of the person.
3 If the age of the person is less than 18 , then we return None.
2
3
1
1 We define a case class of a person with name and age.
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com21
Nested Pattern Matching in Case Classes
case class Address(street: String, city: String, country: String)
case class Person(name: String, age: Int, address:Address)
def checkPrscheckPrscheckPrscheckPrs(p: Person): Option[String] = p match {
case Person(name, age, null) if age > 18 => Some(s"Hi $name! age $age")
case Person(name, age, Address(_,_,ctr)) => Some(s"Hi $name! age $age $ctr")
case _ => None
}
checkPrs(Person("Alice", 19,null)) //> Some(Hi Alice! age 19)
checkPrs(Person("Bill", 15, Address("Scala Lane", "Chicago", "USA"))) //> Some(Hi Bill! age 15 USA)
2 If age > 18 & address = null, then we return the name and age of the person.
3 If the address != null then we return the name, age and the city of the person.
3
2
1 We define two case classes Address and Person. Person contains a subclass Address.
1
Case classes can contain other case classes, and the pattern matching can be nested.
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com22
Matching on regular expression
val email = """(.*)@(.*).(.*)""".r
val date = """(dddd)-(dd)-(dd)""".r
def checkPattern(x:String) : Option[String] = x match{
case email(name,domain,extension) => Some(s"$name $domain $extension")
case date(year, month, day) => Some(s"$year $month $day")
case _ => None
}
A regular expression is used to determine whether a string matches a pattern and,
if it does, to extract or transform the parts that match. Scala supports regular
expressions through Regex class available in the scala.util.matching package.
2
3
1
4
1 We define a regular expressions for email and date by using the method rmethod rmethod rmethod r2
3 If regex of email is matched then extract name, domain and extension
4 If regex of date is matched then extract year, month and day
checkPattern("info@scala.fr") //> Some(info scala fr)
checkPattern("2016-03-26") //> Some(2016 03 26)
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com23
References
• Scala Language Specification, http://www.scala-
lang.org/files/archive/spec/2.11/
• Documentation for the Scala standard library,
http://www.scala-lang.org/api/current/
• Beginning Scala, by Vishal Layka, David Pollak, 2015
• Programming in Scala, by Martin Odersky and al., 2011
• Programming Scala, by Dean Wampler, Alex Payne, 2014
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com24
Mustapha Michrafy PhD
Data Scientist and Expert Optim
at ATOS
Contact : datascience.km@gmail.com
Cyril Valliez PhD
Software Architect at Bouygues
M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com25

Mais conteúdo relacionado

Mais procurados

Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
Masudul Haque
 
16 Java Regex
16 Java Regex16 Java Regex
16 Java Regex
wayn
 
functions
 functions  functions
functions
Gaditek
 

Mais procurados (19)

Perform brute force
Perform brute forcePerform brute force
Perform brute force
 
Python data handling
Python data handlingPython data handling
Python data handling
 
Pattern matching programs
Pattern matching programsPattern matching programs
Pattern matching programs
 
Pattern Matching Part Three: Hamming Distance
Pattern Matching Part Three: Hamming DistancePattern Matching Part Three: Hamming Distance
Pattern Matching Part Three: Hamming Distance
 
Pattern Matching Part Two: k-mismatches
Pattern Matching Part Two: k-mismatchesPattern Matching Part Two: k-mismatches
Pattern Matching Part Two: k-mismatches
 
Kmp
KmpKmp
Kmp
 
Team 1
Team 1Team 1
Team 1
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Computability, turing machines and lambda calculus
Computability, turing machines and lambda calculusComputability, turing machines and lambda calculus
Computability, turing machines and lambda calculus
 
Java: Regular Expression
Java: Regular ExpressionJava: Regular Expression
Java: Regular Expression
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
 
String in python lecture (3)
String in python lecture (3)String in python lecture (3)
String in python lecture (3)
 
16 Java Regex
16 Java Regex16 Java Regex
16 Java Regex
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
 
functions
 functions  functions
functions
 
Pattern Matching Part One: Suffix Trees
Pattern Matching Part One: Suffix TreesPattern Matching Part One: Suffix Trees
Pattern Matching Part One: Suffix Trees
 
Monad Laws Must be Checked
Monad Laws Must be CheckedMonad Laws Must be Checked
Monad Laws Must be Checked
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
smtlecture.4
smtlecture.4smtlecture.4
smtlecture.4
 

Destaque

Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmer
Girish Kumar A L
 

Destaque (20)

Spark SQL principes et fonctions
Spark SQL principes et fonctionsSpark SQL principes et fonctions
Spark SQL principes et fonctions
 
Apache SPARK ML : principes, concepts et mise en œuvre
Apache SPARK  ML : principes, concepts et  mise en œuvre Apache SPARK  ML : principes, concepts et  mise en œuvre
Apache SPARK ML : principes, concepts et mise en œuvre
 
Interface fonctionnelle, Lambda expression, méthode par défaut, référence de...
Interface fonctionnelle, Lambda expression, méthode par défaut,  référence de...Interface fonctionnelle, Lambda expression, méthode par défaut,  référence de...
Interface fonctionnelle, Lambda expression, méthode par défaut, référence de...
 
Scala : programmation fonctionnelle
Scala : programmation fonctionnelleScala : programmation fonctionnelle
Scala : programmation fonctionnelle
 
Spark RDD : Transformations & Actions
Spark RDD : Transformations & ActionsSpark RDD : Transformations & Actions
Spark RDD : Transformations & Actions
 
Base de données graphe, Noe4j concepts et mise en oeuvre
Base de données graphe, Noe4j concepts et mise en oeuvreBase de données graphe, Noe4j concepts et mise en oeuvre
Base de données graphe, Noe4j concepts et mise en oeuvre
 
Les systèmes de représentations sensorielles de la PNL
Les systèmes de représentations sensorielles de la PNLLes systèmes de représentations sensorielles de la PNL
Les systèmes de représentations sensorielles de la PNL
 
Big Data: Concepts, techniques et démonstration de Apache Hadoop
Big Data: Concepts, techniques et démonstration de Apache HadoopBig Data: Concepts, techniques et démonstration de Apache Hadoop
Big Data: Concepts, techniques et démonstration de Apache Hadoop
 
spark_intro_1208
spark_intro_1208spark_intro_1208
spark_intro_1208
 
0712_Seigneurin
0712_Seigneurin0712_Seigneurin
0712_Seigneurin
 
Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmer
 
Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012
 
Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)
 
Apache hive
Apache hiveApache hive
Apache hive
 
Spark - Alexis Seigneurin (Français)
Spark - Alexis Seigneurin (Français)Spark - Alexis Seigneurin (Français)
Spark - Alexis Seigneurin (Français)
 
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
 
Python to scala
Python to scalaPython to scala
Python to scala
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable Language
 
Indexed Hive
Indexed HiveIndexed Hive
Indexed Hive
 
Fun[ctional] spark with scala
Fun[ctional] spark with scalaFun[ctional] spark with scala
Fun[ctional] spark with scala
 

Semelhante a Scala: Pattern matching, Concepts and Implementations

Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2
Bryan O'Sullivan
 
Ai_Project_report
Ai_Project_reportAi_Project_report
Ai_Project_report
Ravi Gupta
 

Semelhante a Scala: Pattern matching, Concepts and Implementations (20)

Clone Refactoring with Lambda Expressions
Clone Refactoring with Lambda ExpressionsClone Refactoring with Lambda Expressions
Clone Refactoring with Lambda Expressions
 
1.Array and linklst definition
1.Array and linklst definition1.Array and linklst definition
1.Array and linklst definition
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 
R for Statistical Computing
R for Statistical ComputingR for Statistical Computing
R for Statistical Computing
 
Advanced matlab codigos matematicos
Advanced matlab codigos matematicosAdvanced matlab codigos matematicos
Advanced matlab codigos matematicos
 
20170509 rand db_lesugent
20170509 rand db_lesugent20170509 rand db_lesugent
20170509 rand db_lesugent
 
ML MODULE 2.pdf
ML MODULE 2.pdfML MODULE 2.pdf
ML MODULE 2.pdf
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
R Basics
R BasicsR Basics
R Basics
 
Rcommands-for those who interested in R.
Rcommands-for those who interested in R.Rcommands-for those who interested in R.
Rcommands-for those who interested in R.
 
Array
ArrayArray
Array
 
Short Reference Card for R users.
Short Reference Card for R users.Short Reference Card for R users.
Short Reference Card for R users.
 
Reference card for R
Reference card for RReference card for R
Reference card for R
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
3_MLE_printable.pdf
3_MLE_printable.pdf3_MLE_printable.pdf
3_MLE_printable.pdf
 
Hands-On Algorithms for Predictive Modeling
Hands-On Algorithms for Predictive ModelingHands-On Algorithms for Predictive Modeling
Hands-On Algorithms for Predictive Modeling
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Ai_Project_report
Ai_Project_reportAi_Project_report
Ai_Project_report
 
Statistics lab 1
Statistics lab 1Statistics lab 1
Statistics lab 1
 

Último

Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get CytotecAbortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Riyadh +966572737505 get cytotec
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
amitlee9823
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
MarinCaroMartnezBerg
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
amitlee9823
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
AroojKhan71
 
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
amitlee9823
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
amitlee9823
 

Último (20)

Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get CytotecAbortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
 
Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Research
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
Capstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics ProgramCapstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics Program
 
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
 
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Anomaly detection and data imputation within time series
Anomaly detection and data imputation within time seriesAnomaly detection and data imputation within time series
Anomaly detection and data imputation within time series
 

Scala: Pattern matching, Concepts and Implementations

  • 1. SCALA PATTERN MATCHING, CONCEPTS AND IMPLEMENTATIONS Mustapha Michrafy PhD M. MICHRAFY & C. VALLIEZ Contact the authors : datascience.km@gmail.com datascience.km@gmail.com1 Cyril Valliez PhD - We thank Oussama Lachiri for helpful discussions.
  • 2. Context This study was presented at the seminar « Data Science Principales, Tools and Applications » at Cermsem laboratory M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com2
  • 3. Goal This study aims to present the pattern matching and its implementation with Scala M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com3
  • 4. Prerequisite Knowledge of • Scala programming language • Functional programming notion M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com4
  • 5. Agenda 1. Basic pattern matching 2. Pattern matching and for loop 3. Pattern alternative: operator « | » 4. Pattern guards 5. Pattern guards and logical operator OR 6. Pattern matching and recursive function 7. Pattern matching on type 8. Pattern matching on tuple 9. Pattern matching on Option 10. Pattern matching on Immutable Collection 11. Pattern matching on Immutable Map 12. Pattern matching on Immutable Set 13. Pattern matching on List 14. Pattern matching on case class 15. Nested Pattern Matching in Case Classes 16. Matching on regular expression M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com5
  • 6. Basic pattern matching : switch-case def getChoicegetChoicegetChoicegetChoice(choicechoicechoicechoice: Int): String = choicechoicechoicechoice matchmatchmatchmatch { case 0 => "no" case 1 => "yes" case ____ => "error" } if choice = 0 then "no" else if choice = 1 then "yes" else then "error" Pattern matching getChoice(1) //> res0: String = yes getChoice(0) //> res1: String = no getChoice(3) //> res2: String = error Testing The wildcard pattern “_” matches any object whatsoever. M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com6
  • 7. Pattern matching and initialization val choicechoicechoicechoice = 0 var mesg ==== choicechoicechoicechoice match { case 0 => "no" case 1 => "yes" case _ => "error" } println(mesg) //> no We can use pattern matching for initializing a variable. M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com7
  • 8. Pattern matching and for loop val choiceschoiceschoiceschoices = List(0,1,10) for( choicechoicechoicechoice <- choices) { choice match { case 0 => println("no") case 1 => println("yes") case _ => println("error") } } //> no //> yes //>error We can use pattern matching with for loop M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com8
  • 9. Pattern alternative: operator « | » def getChoicegetChoicegetChoicegetChoice(choicechoicechoicechoice: Int): String = choicechoicechoicechoice matchmatchmatchmatch { casecasecasecase 0000 =>=>=>=> """"no"no"no"no" casecasecasecase 1111 => "no"=> "no"=> "no"=> "no" case 2 => "yes" case ____ => "error" } if choice in {0,1} then "no" else if choice = 2 then "oui" else then "error" Pattern matching « | » : OR With “|” , we can have multiple tests on a single line def getChoicegetChoicegetChoicegetChoice(choicechoicechoicechoice: Int): String = choicechoicechoicechoice matchmatchmatchmatch { casecasecasecase 0000 | 1 =>| 1 =>| 1 =>| 1 => """"no"no"no"no" case 2 => "yes" case ____ => "error" } getChoice(0) //>res1: String = no getChoice(1) //>res2: String = no Testing M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com9
  • 10. Pattern guards def sign(x:Double) : Byte = x match { case x if x < 0if x < 0if x < 0if x < 0 => -1 case x if x > 0if x > 0if x > 0if x > 0 => 1 case _ => 0 } -1 if x < 0 sing(x) = 1 if x > 0 0 sinon Pattern matching sign(0) //> res1: Byte = 0 sign(2) //> res2: Byte = 1 sign(-2) //> res3: Byte = -1 Testing A pattern guard comes after a pattern and starts with an if. If a pattern guard is present, the match succeeds only if the guard evaluates to true M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com10
  • 11. Pattern guards and logical operator OR def OR(p:Boolean, q: Boolean) : Boolean = (p, q)(p, q)(p, q)(p, q) match { case (x, y) if x==true | y==trueif x==true | y==trueif x==true | y==trueif x==true | y==true => true case _ => false } OR(false, false) //> res1: Boolean = false OR(false, true) //> res2: Boolean = true p q p OR q T T T T F T F T T F F F If (p=T | q=T) then OR(p,q)=true else OR(p,q) =false Testing Pattern matching Transform multiple parameters into one tuple (p,q) M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com11 1 1
  • 12. Pattern matching and recursive function 1 if n = 0 n*(n-1)! otherwise n! ==== def factorialfactorialfactorialfactorial(n: Int): Int = n match { case 0 => 1 case _ => n*factorialfactorialfactorialfactorial(n-1) } def factorialfactorialfactorialfactorial(n:Int) : Int = { def fcfcfcfc(n:Int, p:Int) : Int = ((((n,pn,pn,pn,p)))) match { case (0,c) => c case (m,c) => fc(m-1,p*m) } fcfcfcfc(n,1) } factorial(0) //> res 1: Int = 1 factorial(4) //> res 2: Int = 24 1 Using a tuple (n,p) 2 Initialize an accumulator p to 1 Tail-recursive function M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com12
  • 13. Pattern matching on type def matchByTypematchByTypematchByTypematchByType(z: Any): String = z match { case b:Boolean => s"A boolean : $b" case d:Double => s"A double : $d" case _ => " Unknown type " } 1 2 3 1 If z is Boolean type, b takes its value. 2 If z is the type Double , d takes its value. 3 Use wildcard when z is neither a Boolean type nor a Double type A typed pattern x:T consists of a pattern variable x and a type pattern T. The type of x is the type pattern T, where each type variable and wildcard is replaced by a fresh, unknown type. M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com13
  • 14. Pattern matching on tuple def detectZeroInTupledetectZeroInTupledetectZeroInTupledetectZeroInTuple(x: Tuple2[Any,Any]):String = x match { case (0,0|(0,0)) => "Both values zero." case (0,b) => s"First value is 0 in (0,$b)" case (a, 0) => s"Second value is 0 in ($a, 0)" case _ => "Both nonzero : " + x } 1 The tuple pattern matches input in tuple form and enables the tuple to be decomposed into its constituent elements by using pattern matching variables for each position in the tuple. detectZeroInTuple((0,(0,0))) //> res1: String = Both values zero. detectZeroInTuple((0,0)) //> res2: String = Both values zero. detectZeroInTuple((0,11)) //> res3: String = First value is 0 in (0,11) 1 Match a first pattern if x=(0,0) or x=(0,(0,0)). M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com14
  • 15. Pattern matching on Option def getValueOptiongetValueOptiongetValueOptiongetValueOption[Any](x:Option[Any]) : String = x match{ case Some(x) => s"Some $x" case None => "None " } 1 Option -sealed abstract class- represents optional values. Instances of Option are either an instance of SomeSomeSomeSome or the object None.None.None.None. getValueOption(Option("hello")) //> Some hello getValueOption(Option(null)) //> None getValueOption(Option(())) //> Some () getValueOption(Option(List(10,11))) //Some List(10, 11)) 1 Match a Some(x) if x represents an existing value. Option Some None c c o 2 Match a None if x represents a non-existing value. 2 M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com15
  • 16. Pattern matching on immutable collection import scala.collection.immutable._ def getTypegetTypegetTypegetType(x:Traversable[Any]) : String = x match{ case s:Set[Any] => s"A Immutable Set : $s" case q:Seq[Any] => s"A Immutable Seq : $q" case _ => "A Immutable Map : $x" } getType(Set(0,2,4)) //> A Immutable Set : Set(0, 2, 4) getType(1 to 3) //> Immutable Seq : Range(1, 2, 3) getType(HashMap[Int,Int](1->13)) //> A Immutable Map : Map(1 -> 13) 2 Match a pattern then the type of x is returned Iterable Set Map Seq t t t t traversable t 1 1 2 3 3 Match wildcard then type map is returned This hierarchy is valid for mutable and immutable collections M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com16
  • 17. Pattern matching on Immutable Map import scala.collection.immutable._ def getTypeOfMapgetTypeOfMapgetTypeOfMapgetTypeOfMap(x:Map[Int,Int]) : String = x match{ case _:HashMap[Int,Int] => "A HashMap " case _:TreeMap[Int,Int] => "A TreeMap " case _ => "A ListMap " } getTypeOfMap(HashMap[Int,Int](1->12,2->10)) //>A HashMap getTypeOfMap(TreeMap[Int,Int](1->3,6->6)) //> A TreeMap getTypeOfMap(ListMap[Int,Int](1->13,6->16)) //> A ListMap 1 if x is neither a HashMap nor a TreeMap then x is a ListMap Map HashMap ListMap TreeMap t c c c This hierarchy is valid only for the immutable Map Map is a Trait and all (children) are implementation classes 1 M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com17
  • 18. Pattern matching on immutable Set import scala.collection.immutable._ import scala.collection.immutable.BitSet._ def getTypeOfSetgetTypeOfSetgetTypeOfSetgetTypeOfSet(x:Set[Int]) : String = x match{ case h:HashSet[Int] => "A HashSet " + (h.size,h.sum) case t:TreeSet[Int] => "A TreeSet " + (t.size,t.sum) case l:ListSet[Int] => "A ListSet " + (l.size,l.sum) case z:AnyRef => "type : " + z.getClass.getName } getTypeOfSet(new BitSet1(10)) //> type : scala.collection.immutable.BitSet$BitSet1 getTypeOfSet(HashSet(1,10,12)) //> A HashSet (3,23) getTypeOfSet(TreeSet(1,10)) //> A TreeSet (2,11) getTypeOfSet(ListSet(1,11,12)) //> A ListSet (3,24) Set HashSet ListSet BitSet t c c c This hierarchy is valid only for the immutable Set. The Set is a Trait. BitSet is an abstract class and all children are the class. TreeSet c SortedSet t The subclasses of the abstract class BitSet are BitSet1, BitSet2 and BitSetN M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com18
  • 19. Pattern matching on List 1/2 def sizeListsizeListsizeListsizeList[A](ls : List[A]) : Int = ls match{ case Nil => 0 case _::q => sizeList(q) + 1 } The following function computes the length of a list. It is based on two constructors NilNilNilNil and “::”. sizeList(List()) //> res40: Int = 0 sizeList(List(1)) //> res41: Int = 1 sizeList(List(1,(1,2),3,4)) //> res42: Int = 4 1 If the list is empty, Nil, then we return 0. 2 If ls represents a no-empty list then the length of list is (1+length(q)), where q represents the tail of the list. 1 2 M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com19
  • 20. Pattern matching on List 2/2 def identifyListeidentifyListeidentifyListeidentifyListe(ls: List[Any]): String = ls match { case Nil => "empty list" case _::Nil => "list with single element" case _::_::Nil => "list has two elements" case _ => "list has at least tree elements" } All lists are built from two constructors : NilNilNilNil and “::”.... NilNilNilNil represents a empty list :::::::: builds a non empty list characterized by a head and a tail. identifyListe(Nil) //> empty list identifyListe(List((1,2))) //> list with single element identifyListe(List("Scala", 3)) //> list has two elements identifyListe(List(1,2,3)) //> list has at least tree elements M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com20
  • 21. Pattern matching on case class case class PersonPersonPersonPerson(name: String, age: Int) def validateAgevalidateAgevalidateAgevalidateAge(p: Person): Option[String] = p match { case Person(name, age) if age > 18 => Some(s"Hi $name! age $age") case _ => None } Case classes are classes that get to String, hashCode, and equals methods automatically. It provide a recursive decomposition mechanism via pattern matching validateAge(Person("Alice", 19)) //> Some(Hi Alice! age 19) validateAge(Person("Bill", 15)) //> None 2 If the age is greater than18 , then we return the name and age of the person. 3 If the age of the person is less than 18 , then we return None. 2 3 1 1 We define a case class of a person with name and age. M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com21
  • 22. Nested Pattern Matching in Case Classes case class Address(street: String, city: String, country: String) case class Person(name: String, age: Int, address:Address) def checkPrscheckPrscheckPrscheckPrs(p: Person): Option[String] = p match { case Person(name, age, null) if age > 18 => Some(s"Hi $name! age $age") case Person(name, age, Address(_,_,ctr)) => Some(s"Hi $name! age $age $ctr") case _ => None } checkPrs(Person("Alice", 19,null)) //> Some(Hi Alice! age 19) checkPrs(Person("Bill", 15, Address("Scala Lane", "Chicago", "USA"))) //> Some(Hi Bill! age 15 USA) 2 If age > 18 & address = null, then we return the name and age of the person. 3 If the address != null then we return the name, age and the city of the person. 3 2 1 We define two case classes Address and Person. Person contains a subclass Address. 1 Case classes can contain other case classes, and the pattern matching can be nested. M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com22
  • 23. Matching on regular expression val email = """(.*)@(.*).(.*)""".r val date = """(dddd)-(dd)-(dd)""".r def checkPattern(x:String) : Option[String] = x match{ case email(name,domain,extension) => Some(s"$name $domain $extension") case date(year, month, day) => Some(s"$year $month $day") case _ => None } A regular expression is used to determine whether a string matches a pattern and, if it does, to extract or transform the parts that match. Scala supports regular expressions through Regex class available in the scala.util.matching package. 2 3 1 4 1 We define a regular expressions for email and date by using the method rmethod rmethod rmethod r2 3 If regex of email is matched then extract name, domain and extension 4 If regex of date is matched then extract year, month and day checkPattern("info@scala.fr") //> Some(info scala fr) checkPattern("2016-03-26") //> Some(2016 03 26) M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com23
  • 24. References • Scala Language Specification, http://www.scala- lang.org/files/archive/spec/2.11/ • Documentation for the Scala standard library, http://www.scala-lang.org/api/current/ • Beginning Scala, by Vishal Layka, David Pollak, 2015 • Programming in Scala, by Martin Odersky and al., 2011 • Programming Scala, by Dean Wampler, Alex Payne, 2014 M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com24
  • 25. Mustapha Michrafy PhD Data Scientist and Expert Optim at ATOS Contact : datascience.km@gmail.com Cyril Valliez PhD Software Architect at Bouygues M. MICHRAFY & C. VALLIEZ datascience.km@gmail.com25