Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (==)
like image 713
fredoverflow Avatar asked Dec 11 '13 09:12

fredoverflow


Video Answer


1 Answers

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
like image 63
tmbo Avatar answered Oct 22 '22 01:10

tmbo