对组件的平等功能

fre*_*low 8 haskell scala tuples equality currying

Scala中是否有一个函数比较一对中的两个组件是否相等?就像是:

def pairEquals[A, B](pair: Pair[A, B]): Boolean = (pair._1 == pair._2)
Run Code Online (Sandbox Code Playgroud)

在Haskell中,那将是:

uncurry (==)
Run Code Online (Sandbox Code Playgroud)

tmb*_*mbo 7

标准库中没有类似的东西.但您可以轻松扩展Pairs以获得您的行为

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
Run Code Online (Sandbox Code Playgroud)

编辑:

另一种方法是: x == x.swap

EDIT2:

这是第三种使用equals函数的方法,并使用与uncurryhaskell 类似的结构.

// 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
Run Code Online (Sandbox Code Playgroud)