I've a question regarding this pattern matching in scala:
val div: (Double, Double) => Double = {
case (x, y) if y != 0 => x / y
}
I've understand how pattern matching works and its syntaxis in scala, but this expression drives me crazy. How does complier knows that x and y is an arguments of the function and pattern match on them?
What Does Pattern Matching Mean? Pattern matching in computer science is the checking and locating of specific sequences of data of some pattern among raw data or a sequence of tokens. Unlike pattern recognition, the match has to be exact in the case of pattern matching.
Pattern matching algorithms are the algorithms that are used to figure out whether a specific string pattern occurs in a string text. Two of the most widely used pattern matching algorithms are the Naive Algorithm for pattern matching and the pattern matching algorithm using finite automata.
For example, x* matches any number of x characters, [0-9]* matches any number of digits, and . * matches any number of anything. A regular expression pattern match succeeds if the pattern matches anywhere in the value being tested.
The rules for this are defined in section 8.5 "Pattern Matching Anonymous Functions" of the Scala Language Specification. If using an anonymous function with pattern matching, the type must be partially provided. You do that by saying the type is (Double, Double) => Double
, which is shorthand for Function2[Double, Double, Double]
.
Now:
If the expected type is
scala.Function k [S1,…,Sk, R]
, the expression is taken to be equivalent to the anonymous function:(x1:S1,…,xk:Sk) => (x1,…,xk) match { case p1 => b1 … case pn => bn }
So no matter what the arity of your function, the pattern match is passed a tuple of the function's arguments, hence you can use the regular tuple extractor syntax.
So your example is short for
val div: (Double, Double) => Double = (a, b) => (a, b) match {
case (x, y) if y != 0 => x / y
}
or
val div = (a: Double, b: Double) => (a, b) match {
case (x, y) if y != 0 => x / y
}
The naming of the extractor parameters x
and y
is up to your imagination. You decide how to call the resulting elements of the extractor, you could as well write case (foo, bar) => ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With