采用 Ordered[A] 的任何子类型的函数的 Scala 语法是什么? [英] What's the Scala syntax for a function taking any subtype of Ordered[A]?
问题描述
我想编写一个函数,它可以在任何具有总排序的 Scala 类型上运行(即我可以在其上使用 '<').那的语法是什么?我想出的最好的是
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
但是,当我尝试从 REPL 使用它时,这不起作用:
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))
本质上,我相信我想要这个 Haskell 代码的等价物:
Essentially, I believe I want the equivalent of this Haskell code:
lessThan :: (Ord a) => a -> a -> Bool
lessThan x y = x < y
我在 Debian 系统上使用 scala 2.7.3.
I'm using scala 2.7.3 on a Debian system.
我错过了什么,在哪里?
What am I missing, and where?
推荐答案
Scala 中 Haskell 类型类的等效项是通过隐式完成的.有两种方法可以做你想做的
The equivalent of Haskell's type classes in Scala is done via implicits. There are two ways to do what you want
第一个是视图边界
scala> def lessThan[T <% Ordered[T]](x : T, y : T) = x < y
lessThan: [T](T,T)(implicit (T) => Ordered[T])Boolean
scala> lessThan(1,2)
res0: Boolean = true
第二个是带有隐式参数
scala> def lessThan[T](x : T, y : T)(implicit f : T => Ordered[T]) = x < y
lessThan: [T](T,T)(implicit (T) => Ordered[T])Boolean
scala> lessThan(4,3)
res1: Boolean = false
前者是后者的语法糖.后者允许更大的灵活性.
The former is syntax sugar for the later. The later allows more flexibility.
这篇关于采用 Ordered[A] 的任何子类型的函数的 Scala 语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!