Scala pattern matching with tuple: matching equal values in the tuple

I have created a function to retrieve a given value from the Pascal Triangle and I've used if statements. Now I want to refactor the function to use pattern matching.

My if based function looks like this:

def valueAt(row: Int, column: Int): Int = {
  // ...
  else if (row == column) 1 // last column
  // 
}

My second version of this function, using pattern matching has the following signature:

def valueAt2(row: Int, column: Int): Int = (row, column) match {
  // ...
}

Is it possible to define a case for when the row and column have the same value?

I have tried using the same variable name in the case , like this:

case (x, x) => 1 // last column

And I have also tried to use the value of the row in the column, like this:

case (_, row) => 1 // last column

But they don't work. In the first case I have a compilation error and in the second the IDE says that I'm shadowing the variable row from the match .

It this possible?

Thanks.


For the first one, use an if guard:

(1, 2) match { case (x, y) if x == y => 1; ... }

For the second one, when you want to match a variable (instead of binding and shadowing it), you can use backticks (`):

(1, 2) match { case (_, `row`) => 1; ... }

You can use a guard , which is a part of a case expression that can check non-stable conditions, and not surprisingly resembles an if statement:

 (row, column) match {
    case (x, y) if x == y => 1
    // other cases...
 }

Note that inputs not matching this guard (ie for which x != y ) would continue to check the other cases, so, for example, another case case (x, y) => ... can follow, and assume x != y .

链接地址: http://www.djcxy.com/p/62640.html

上一篇: 为什么HTTP代理能够支持像IRC和FTP这样的协议?

下一篇: 与元组匹配的Scala模式:在元组中匹配相等的值