采用 Ordered[A] 任何子类型的函数的 Scala 语法是什么?
我想编写一个适用于任何具有全排序的 Scala 类型的函数(即我可以在其上使用“<”)。 其语法是什么? 我想出的最好的办法是
def lessThan[T <: Ordered[T]](x: T, Y: T) = x < y
,当我尝试从 REPL 中使用它时,这不起作用:
scala> lessThan(1, 2)
<console>:8: error: inferred type arguments [Int] do not conform to method lessThan's type parameter bounds [T <: Ordered[T]]
lessThan(1, 2)
^
scala> import runtime._
import runtime._
scala> lessThan(new RichInt(1), new RichInt(2))
<console>:8: error: inferred type arguments [scala.runtime.RichInt] do not conform to method lessThan's type parameter bounds [T <: Ordered[T]]
lessThan(new RichInt(1), new RichInt(2))
本质上,我相信我想要与此 Haskell 代码等效的代码:
lessThan :: (Ord a) => a -> a -> Bool
lessThan x y = x < y
我在 Debian 上使用 scala 2.7.3系统。
我缺少什么,在哪里?
I want to write a function that works on any Scala type with a total ordering (i.e. I can use '<' on it). What's the syntax for that? The best I've come up with is
def lessThan[T <: Ordered[T]](x: T, Y: T) = x < y
That doesn't work, though, when I try using it from the REPL:
scala> lessThan(1, 2)
<console>:8: error: inferred type arguments [Int] do not conform to method lessThan's type parameter bounds [T <: Ordered[T]]
lessThan(1, 2)
^
scala> import runtime._
import runtime._
scala> lessThan(new RichInt(1), new RichInt(2))
<console>:8: error: inferred type arguments [scala.runtime.RichInt] do not conform to method lessThan's type parameter bounds [T <: Ordered[T]]
lessThan(new RichInt(1), new RichInt(2))
Essentially, I believe I want the equivalent of this Haskell code:
lessThan :: (Ord a) => a -> a -> Bool
lessThan x y = x < y
I'm using scala 2.7.3 on a Debian system.
What am I missing, and where?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Scala 中 Haskell 类型类的等效项是通过隐式完成的。 有两种方法可以实现您想要的功能
第一种是使用视图边界
第二种是使用隐式参数
前者是后者的语法糖。 后者允许更大的灵活性。
The equivalent of Haskell's type classes in Scala is done via implicits. There are two ways to do what you want
The first is with view bounds
The second is with an implicit parameter
The former is syntax sugar for the later. The later allows more flexibility.