I find myself writing code like the following:
val b = a map (entry => entry match { case ((x,y), u) => ((y,x), u) } )
I would like to write it differently, if only this worked:
val c = a map (((x,y) -> u) => (y,x) -> u )
Is there any way I can get something close to this?
Notes. Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.
Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.
Believe it or not, this works:
val b = List(1, 2) b map { case 1 => "one" case 2 => "two" }
You can skip the p => p match
in simple cases. So this should work:
val c = a map { case ((x,y) -> u) => (y,x) -> u }
In your example, there are three subtly different semantics that you may be going for.
Map over the collection, transforming each element that matches a pattern. Throw an exception if any element does not match. These semantics are achieved with
val b = a map { case ((x, y), u) => ((y, x), u) }
Map over the collection, transforming each element that matches a pattern. Silently discard elements that do not match:
val b = a collect { case ((x, y), u) => ((y, x), u) }
Map over the collection, safely destructuring and then transforming each element. These are the semantics that I would expect for an expression like
val b = a map (((x, y), u) => ((y, x), u)))
Unfortunately, there is no concise syntax to achieve these semantics in Scala. Instead, you have to destructure yourself:
val b = a map { p => ((p._1._2, p._1._1), p._2) }
One might be tempted to use a value definition for destructuring:
val b = a map { p => val ((x,y), u) = p; ((y, x), u) }
However, this version is no more safe than the one that uses explicit pattern matching. For this reason, if you want the safe destructuring semantics, the most concise solution is to explicitly type your collection to prevent unintended widening and use explicit pattern matching:
val a: List[((Int, Int), Int)] = // ... // ... val b = a map { case ((x, y), u) => ((y, x), u) }
If a
's definition appears far from its use (e.g. in a separate compilation unit), you can minimize the risk by ascribing its type in the map call:
val b = (a: List[((Int, Int), Int)]) map { case ((x, y), u) => ((y, x), u) }
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