gpt4 book ai didi

Scala 实数区间,整数区间

转载 作者:行者123 更新时间:2023-12-04 20:17:19 27 4
gpt4 key购买 nike

我如何定义这两个简单的 Interval 类的样板消除父类(super class)?

class IntInterval(val from: Int, val to: Int) { 
def mid: Double = (from+to)/2.0
def union(other: IntInterval) = IntInterval(from min other.from, to max other.to)
}

class DoubleInterval(val from: Double, val to: Double) {
def mid: Double = (from+to)/2.0
def union(other: DoubleInterval) = DoubleInterval(from min other.from, to max other.to)
}

我试过
class Interval[T <: Number[T]] (val from: T, val to: T) { 
def mid: Double = (from.doubleValue+to.doubleValue)/2.0
def union(other: IntInterval) = Interval(from min other.from, to max other.to)
}

但是 min 和 max 没有在 union 方法中编译(因为 Number[T] 没有 min/max)。

你能提供一个优雅的父类(super class),它以一种整洁的、代码一次且避免样板的方式处理 mid 和 union 方法吗?

最佳答案

我认为您正在寻找 scala.math.Numeric类型类:

class Interval[T] (val from: T, val to: T)(implicit num: Numeric[T]) { 
import num.{mkNumericOps, mkOrderingOps}

def mid: Double = (from.toDouble + to.toDouble)/2.0
def union(other: Interval[T]) = new Interval(from min other.from, to max other.to)
}

关于Scala 实数区间,整数区间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10568186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com