What's the Scala syntax for a function taking any subtype of Ordered[A]?

Deadly 提交于 2019-12-21 03:32:36

问题


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?


回答1:


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

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

The second is with an implicit parameter

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.



来源:https://stackoverflow.com/questions/691422/whats-the-scala-syntax-for-a-function-taking-any-subtype-of-ordereda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!