Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern Matching Function Arguments

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?

like image 261
Sayat Satybald Avatar asked Nov 09 '14 11:11

Sayat Satybald


People also ask

How do you explain pattern matching?

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.

What is pattern matching problem?

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.

What is pattern matching give an example?

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.


1 Answers

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) => ...

like image 191
0__ Avatar answered Oct 21 '22 01:10

0__