scala - 如何将类型限制为 Scala 中的特定类型

标签 scala generics numeric

我想按照此处给出的方式修改此代码: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))}
}

还可以使用 LongFloatDouble(因为这些是 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
  }
}

您可以看到运行的代码 here .

关于scala - 如何将类型限制为 Scala 中的特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67638461/

相关文章:

function - typescript 从传递的函数返回类型推断返回类型

python - 在 Python 中对列表进行数字排序

java - AWS S3 Java SDK : RequestClientOptions. setReadLimit

scala - 案例类的自定义提取器在模式匹配中不起作用

mysql - 如何在 Slick 中使用 IN 子句?

java - 怎么 ?与所说的对象不同?

scala - Akka 和 Vert.x 消息传递模型的区别

c# - 从列表递归创建树

r - 尝试获取 R 中的商作为数字对象

mysql - 用空字符串替换非字母数字字符 MYSQL