鉴于我有两个Seq[M]
和一个比较函数compare(m1:M, m2:M):Int
,我如何为两个序列编写比较函数。
def compare[M](s1:Seq[M], s2:Seq[M], cmp:(M,M)=>Int) : Int = {
???
}
我自己在迭代序列时实现这一点没有问题,但我确信已经在Scala库中做了一些准备工作。我查看了Ordering
类和对象,但是看到所有隐式树的森林都有问题。
编辑:任何可以使用seqDerivedOrdering
的方法
https://github.com/scala/scala/blob/v2.11.2/src/library/scala/math/Ordering.scala#L1除了复制代码?
答案 0 :(得分:3)
您可以使用seqDerivedOrdering
但仍需提供隐式排序,因为它不会(M,M) => Int
。你可以尝试这样的事情:
def compare[M](s1: Seq[M], s2: Seq[M])(cmp: (M, M) => Int): Int = {
implicit val orderM = new Ordering[M] {
override def compare(x: M, y: M): Int = cmp(x, y)
}
scala.math.Ordering.Implicits.seqDerivedOrdering[Seq, M].compare(s1, s2)
}
也许是相同代码的稍微好一点的版本:
def compare[M](s1: Seq[M], s2: Seq[M])(cmp: (M, M) => Int): Int = {
import scala.math.Ordering.Implicits._
implicit val orderM = new Ordering[M] {
override def compare(x: M, y: M): Int = cmp(x, y)
}
implicitly[Ordering[Seq[M]]].compare(s1, s2)
}
或者,我们可以做得更好:
import scala.math.Ordering.Implicits._
def compare[M](s1: Seq[M], s2: Seq[M])(cmp: (M, M) => Int)(implicit ord: Ordering[Seq[M]]): Int = {
implicit val orderM = new Ordering[M] {
override def compare(x: M, y: M): Int = cmp(x, y)
}
ord.compare(s1, s2)
}
答案 1 :(得分:1)
据我所知,没有内置任何东西。最紧凑的可能就像
def compare[M](s1: Seq[M], s2: Seq[M], cmp: (M, M) => Int): Int = {
val diff = (s1 zip s2).find(x => cmp(x._1, x._2) != 0)
diff.map(x => cmp(x._1, x._2)).getOrElse(s1.length compare s2.length)
}
使用迭代器的解决方案更有效但不太紧凑。