[英]How to constrain types to specific types in scala
我想修改这里给出的代码: Find min and max elements of array
def minMax(a: Array[Int]) : (Int, Int) = {
if (a.isEmpty) throw new java.lang.UnsupportedOperationException("array is empty")
a.foldLeft((a(0), a(0)))
{ case ((min, max), e) => (math.min(min, e), math.max(max, e))}
}
也可以使用Long
, Float
和Double
(因为这些是 scala.math.min/max 接受的类型。我试过:
def getMinAndMax[@specialized(Int,Long,Float,Double) T](x: Seq[T]) : (T, T) = {
if (x.isEmpty) throw new java.lang.UnsupportedOperationException("seq is empty")
x.foldLeft((x.head, x.head))
{ case ((min, max), e) => (math.min(min, e), math.max(max, e))}
}
但这也不能编译。 有什么建议吗?
你想要一个typeclass 。 具体来说,在这种情况下,您需要从标准库中Ordering
。
// It is more idiomatic to return an Option rather than throwing an exception,
// that way callers may decide how to handle that case.
def getMinAndMax[T : Ordering](data: IterableOnce[T]): Option[(T, T)] = {
import Ordering.Implicits._ // Provides the comparison operators: < & >
data.iterator.foldLeft(Option.empty[(T, T)]) {
case (None, t) =>
Some((t, t))
case (current @ Some((min, max)), t) =>
if (t < min) Some((t, max))
else if (t > max) Some((min, t))
else current
}
}
您可以看到这里运行的代码。
另一种方法是使用来自Numeric
的 min/max :
def minMax[T](s: Seq[T])(implicit num: Numeric[T]): (T, T) = {
if (s.isEmpty) throw new java.lang.UnsupportedOperationException("seq is empty")
s.foldLeft((s.head, s.head)) {case ((min, max), e) => (num.min(min, e), num.max(max, e))}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.