Everybody says that pattern matching is a great feature in functional languages. Why?
Can’t I simple use ifs and switch cases for everything?
I’d like to understand the advantages of using pattern matching instead of regular procedural programming ifs and switch cases
Advertisement
Answer
I’d first like to note that you don’t use pattern matching “instead” of switch statements. Scala doesn’t have switch
statements, what it does have is match blocks, with cases inside that superficially look very similar to a switch statement.
Match blocks with pattern matching does everything that switch
does, and much more.
A) It’s not restricted to just primitives and other types that Oracle have chosen to “bless” in the language spec (Strings and Enums). If you want to match on your own types, go right ahead!
B) Pattern matching can also extract. For example, with a tuple:
val tup = ("hello world", 42) tup match { case (s,i) => println("the string was " + s) println("the number was " + i }
With a list:
val xs = List(1,2,3,4,5,6) xs match { case h :: t => // h is the head: 1 // t is the tail: 2,3,4,5,6 // The :: above is also an example of matching with an INFIX TYPE }
With a case class
case class Person(name: String, age: Int) val p = Person("John Doe", 42) p match { case Person(name, 42) => //only extracting the name here, the match would fail if the age wasn't 42 println(name) }
C) pattern matching can be used in value assignment and for-comprehensions, not just in match blocks:
val tup = (19,73) val (a,b) = tup for((a,b) <- Some(tup)) yield a+b // Some(92)
D) match blocks are expressions, not statements
This means that they evaluate to the body of whichever case was matched, instead of acting entirely through side-effects. This is crucial for functional programming!
val result = tup match { case (a,b) => a + b }