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
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 = ();
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.
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!") }
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
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