scala - 检查范围是否包含Scala中的值的通用方法
问题描述
我想编写一个包含范围端点的泛型类,但泛型版本会返回编译错误:value >= is not a member of type parameter A
final case class MinMax[A <: Comparable[A]](min: A, max: A) {
def contains[B <: Comparable[A]](v: B): Boolean = {
(min <= v) && (max >= v)
}
}
具体版本按预期工作:
final case class MinMax(min: Int, max: Int) {
def contains(v: Int): Boolean = {
(min <= v) && (max >= v)
}
}
MinMax(1, 3).contains(2) // true
MinMax(1, 3).contains(5) // false
解决方案
你离得太近了。
在Scala中,我们有Ordering
一个typeclass来表示可以比较相等和小于 & 大于的类型。
因此,您的代码可以这样编写:
// Works for any type A, as long as the compiler can prove that the exists an order for that type.
final case class MinMax[A](min: A, max: A)(implicit ord: Ordering[A]) {
import ord._ // This is want brings into scope operators like <= & >=
def contains(v: A): Boolean =
(min <= v) && (max >= v)
}
推荐阅读
- queue - 如何在 micropython 和 ev3dev 中使用队列
- xamarin.forms - Xamarin Forms Picker 类似 iOS Picker
- flutter - 在颤动中自动缩放网格内的文本
- c - C中的函数在被调用两次后返回先前的值
- reactjs - 在数组和映射结果中反应 setState 对象
- html - Outlook 不在 html 电子邮件中为桌面堆叠 TD
- tensorflow - 使用棕色数据集(NLTK)的单词相似度的skip-gramm(word2vec)模型的准确性
- notepad++ - 替换记事本++中的每隔一个空行
- android - MotionLayout 忽略填充
- sql - 将 2 个字符串列(如年和月)合并为日期格式列