7

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 (==)
fredoverflow
  • 256,549
  • 94
  • 388
  • 662

1 Answers1

7

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
tmbo
  • 1,317
  • 10
  • 26