Introduction to Scala Part3: Option & Pattern Matching
Bubu
3,033 views
Pattern Matching
Pattern matching is a generalization of switch from C/Java to class hierarchies. It’s expressed in Scala using the keyword match.
Examples:
def eval(e: Expr): Int = e match {
case Number(n) => n
case Sum(e1, e2) => eval(e1) + eval(e2)
}
Rules
- Match is followed by a sequence of cases
- Each case associates an expression to a pattern
- An exception MatchError is thrown if no pattern matches the value of the selector
Pattern forms
Patterns are constructed from:
- Constructors : Number, Sum, etc.
- Variables : n, e1, e2, etc.
- Wildcard patterns : _
- Constants : 1 , true
Variables always begin with a lowercase letter. The same variable name can only appear once in a pattern (Sum(x, x) is not a legal pattern)
Constructors and the names of constants begin with a capital letter, with the exception of the reserved words: null, true ,false
headOption
sum
multiply
fibonacci
lastOption
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Suggested playgrounds
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package fp101.tp03.patternmatching
object ExercicePatternMatching {
/**
*
* Use list match { ...}
*/
def headOption[T](list: List[T]): Option[T] = ???
/**
*
* Use l match { ...}
*/
def sum(list: List[Int]): Int = ???
/**
*
* Use list match {... }
*/
def multiply(list: List[Int]): Int = ???
/**
*
* use n match {...}
* fibonacci(n) = fibonacci(n -1) + fibonacci(n - 2)
* base: fibonacci(0) => 0
* fibonacci(1) => 1
* fibonacci(< 0) => 0
*
*/
def fibonacci(n: Int): Int = ???
/**
* use l match {...}
* This is harder.
* You have to read the documentation of List to find the good operation of composition
*
* http://www.scala-lang.org/api/current/#scala.collection.immutable.List