Introduction to Scala Part3: Option & Pattern Matching
Bubu
4,418 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content
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
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
*
Enter to Rename, Shift+Enter to Preview