Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching on tuple using comparison operator

I would like to match on tuple pattern, but I can not find any solution how to match using comparison operators. My code is:

myTuple  match {       
      case (-1,-1,true) => ...       
      case (_>=0,-1,_) =>  ...
    }

This gives give compile time error. I also tried to use if guard, but as I see it can not be applied this way:

 case (_ if _>=0,-1,_) =>  ...

Is my approach correct or should I solve this on an different way? Thanks Zoltan

like image 934
HamoriZ Avatar asked Jul 17 '12 13:07

HamoriZ


People also ask

How do you match tuples in Python?

Tuple Matching in Python is a method of grouping the tuples by matching the second element in the tuples. It is achieved by using a dictionary by checking the second element in each tuple in python programming. However, we can make new tuples by taking portions of existing tuples. tup1 = ();

How does tuple comparison work?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.

How would you compare two tuples to ensure their values are identical?

To compare tuples, just use the == operator, like this: let singer = ("Taylor", "Swift") let alien = ("Justin", "Bieber") if singer == alien { print("Matching tuples!") } else { print("Non-matching tuples!") }


1 Answers

The syntax is wrong, you should use guard as follows:

myTuple  match {       
  case (-1,-1,true) => ...
  case (x,-1,_) if x >= 0 =>  ...
  case _ => ... // default
}

There are a lot of good introduction to scala pattern matching on the web. Here is the first detailed one, I've found on google: Playing with Scala's pattern matching

like image 158
Nicolas Avatar answered Oct 01 '22 04:10

Nicolas