我认为主要问题是数字类型的转换。所以让我们编码:
trait NumericConversion[X, Y] {
def convert(x: X): Y
}
当然,必须指定那个抽象概念:(例如)
implicit object Int2IntNumericConversion extends NumericConversion[Int, Int] {
def convert(i: Int): Int = i
}
implicit object Double2DoubleNumericConversion extends NumericConversion[Double, Double] {
def convert(d: Double): Double = d
}
implicit object Int2DoubleNumericConversion extends NumericConversion[Int, Double] {
def convert(i: Int): Double = i.toDouble
}
现在比较方法如下:
def compareTwoNumbers1[N1, N2, N3](n1: N1, n2: N2)
(implicit conv1: NumericConversion[N1, N3],
conv2: NumericConversion[N2, N3],
ord: Ordering[N3]): Int = {
ord compare (conv1 convert n1, conv2 convert n2)
}
用法:
compareTwoNumbers1[Int, Double, Double](3, 8D) // -1
可惜了,我们必须显式声明类型参数,所以我尝试了:
def compareTwoNumbers2[N3] = new {
def apply[N1, N2](n1: N1, n2: N2)(implicit conv1: NumericConversion[N1, N3],
conv2: NumericConversion[N2, N3],
ord: Ordering[N3]): Int = {
ord compare (conv1 convert n1, conv2 convert n2)
}
}
这简化为一种类型的参数:
compareTwoNumbers2[Double](3, 8D) // -1
不满意,所以我尝试了这个:
trait NumericUpperBound[Num1, Num2, UpperBound]
implicit object NumericUpperBoundIDD extends NumericUpperBound[Int, Double, Double]
implicit object NumericUpperBoundDID extends NumericUpperBound[Double, Int, Double]
使用新的比较方法:
def compareTwoNumbers3[N1, N2, N3](n1: N1, n2: N2)
(implicit nub: NumericUpperBound[N1, N2, N3],
conv1: NumericConversion[N1, N3],
conv2: NumericConversion[N2, N3],
ord: Ordering[N3]): Int = {
ord compare (conv1 convert n1, conv2 convert n2)
}
现在它起作用了:
compareTwoNumbers3(3, 8D) // -1
当然,必须为所有原语创建类型类。但是稍后将其扩展到BigInt
等是灵活的。
编辑
@wvxvw 的评论提到了一个矩阵,它NumericUpperBounds
启发了我绕过矩阵,这是一个运行示例(暂时不包括在内)Byte
:Short
trait ==>[X, Y] extends (X => Y)
object ==> {
def apply[X, Y](f: X => Y): X ==> Y = {
new (X ==> Y) {
def apply(x: X): Y = f(x)
}
}
}
implicit val Int2LongNumericConversion = ==> { x: Int => x.toLong }
implicit val Int2FloatNumericConversion = ==> { x: Int => x.toFloat }
implicit val Int2DoubleNumericConversion = ==> { x: Int => x.toDouble }
implicit val Long2FloatNumericConversion = ==> { x: Long => x.toFloat }
implicit val Long2DoubleNumericConversion = ==> { x: Long => x.toDouble }
implicit val Float2DoubleNumericConversion = ==> { x: Float => x.toDouble }
implicit def reflexiveNumericConversion[X]: X ==> X = new (X ==> X) { def apply(x: X): X = x }
trait NumericUpperBound[Num1, Num2, UpperBound]
implicit def reflexiveNumericUpperBound[X]: NumericUpperBound[X, X, X] = new NumericUpperBound[X, X, X] {}
implicit def inductiveNumericUpperBound1[X, Y](implicit ev: X ==> Y): NumericUpperBound[Y, X, Y] = new NumericUpperBound[Y, X, Y] {}
implicit def inductiveNumericUpperBound2[X, Y](implicit ev: X ==> Y): NumericUpperBound[X, Y, Y] = new NumericUpperBound[X, Y, Y] {}
def compareTwoNumbers[N1, N2, N3](n1: N1, n2: N2)
(implicit nub: NumericUpperBound[N1, N2, N3],
conv1: N1 ==> N3,
conv2: N2 ==> N3,
ord: Ordering[N3]): Int = {
ord compare (n1, n2)
}
compareTwoNumbers(9L, 13) // -1