简体   繁体   中英

Equality function for pair components

Is there a function in Scala that compares the two components of a pair for equality? Something like:

def pairEquals[A, B](pair: Pair[A, B]): Boolean = (pair._1 == pair._2)

In Haskell, that would be:

uncurry (==)

There is nothing like that in the standard library. But you can easily extend Pairs to have your behaviour

implicit class PimpedTuple[A,B](tp: Tuple2[A,B]) {
  def pairEquals = tp._1 == tp._2
}

val x = (2, 3)
x.pairEquals  // false

val y = (1, 1)
y.pairEquals  // true

Edit:

Another way to do it would be: x == x.swap

Edit2:

Here is a third way which plays around with the equals function and uses a similar construct as the uncurry in haskell.

// This is necessary as there is no globally available function to compare values
def ===(a:Any, b: Any) = a == b

val x = (1,1)
(===_).tupled(x)   // true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM