寻找适用于 Scala 2.7.7 和 2.8 脚本的类型类用法示例

发布于 2024-10-07 04:29:08 字数 163 浏览 0 评论 0原文

您好,我正在寻找 Scala 中类型类用法的快速示例,该示例可以在 2.7.7 和 2.8 环境中工作。

我见过的所有示例都只能在 2.8 中运行,但我被告知类型类也可以在 2.7.7 中实现。

唯一的其他要求是该用法必须能够在脚本中运行。

任何例子表示赞赏!谢谢

Hi I'm looking for a quick example of type class usage in Scala that will work in both 2.7.7 and 2.8 environments.

All of the examples that I've seen only work in 2.8, but I've been told that type classes are implementable in 2.7.7 as well.

The only other requirement is that the usage must be able to work in a script.

Any examples appreciated! Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

逆光下的微笑 2024-10-14 04:29:08

我想你可以这样做:

def max[A](list: List[A])(implicit ord: Ordering[A]): A = {
  list.tail.foldLeft(list.head) ((a, b) => if (ord.lt(a, b)) b else a)
}

implicit def toOrdering[A <% Ordered[A]]: Ordering[A] = new Ordering[A] {
    def compare(a: A, b: A): Int = (a < b, b < a) match {
        case (true, _) => -1
        case (_, true) => 1
        case _ => 0
    }
}

println(max(List(1, 2, 3, 2, 1)))

代码在 Scala 2.7.7 和 2.8.0 中运行(现在在两者中都经过测试),尽管隐式定义在 Scala 2.8 中是不必要的(在某些情况下可能有害)。

I suppose you could do something like this:

def max[A](list: List[A])(implicit ord: Ordering[A]): A = {
  list.tail.foldLeft(list.head) ((a, b) => if (ord.lt(a, b)) b else a)
}

implicit def toOrdering[A <% Ordered[A]]: Ordering[A] = new Ordering[A] {
    def compare(a: A, b: A): Int = (a < b, b < a) match {
        case (true, _) => -1
        case (_, true) => 1
        case _ => 0
    }
}

println(max(List(1, 2, 3, 2, 1)))

The code runs in both Scala 2.7.7 and 2.8.0 (tested right now in both), though the implicit definition is unnecessary (and possibly harmful in some situations) in Scala 2.8.

一曲琵琶半遮面シ 2024-10-14 04:29:08

我采用了以下解决方案:

//---------- Classes without needed behavior
case class Point(x: Double, y: Double)
trait Shape {}
case class Circle(center: Point, radius: Double) extends Shape {}
case class Rectangle(lowerLeft: Point, upperRight: Point) extends Shape {}


val circle = Circle(Point(1.0, 2.0), 5.0)
val rectangle = Rectangle(Point(-2.0, -1.0), Point(4.0, 5.0))


//----------- Support for new behavior I want to add

// Create exception to handle non supported subclasses
case class NewMethodNotSupported(a: Any)
    extends RuntimeException(a.toString + ".newMethod() not supported")

class NewBehavior(shape: Shape) {
    def newMethod() = shape match {
        case c: Circle => doMethod(c)
        case r: Rectangle => doMethod(r)
        case _ => throw NewMethodNotSupported(shape)
    }
    private
    def doMethod(s: Shape) = println(s) // print to standard out.
}

object NewBehavior {
    // invoked by the compiler
    implicit def shapeToNewBehavior(s: Shape) = new NewBehavior(s)
}

// bring the implicit method in scope
import NewBehavior._
// --------- End of new behavior support        


// Test behavior support:
println("Test that new behavior is added:")
circle.newMethod()
rectangle.newMethod()

// Create a non supported shape class
case class Triangle(vertex1: Point,
        vertex2: Point, vertex3: Point) extends Shape {}

val triangle = Triangle(Point(-1.0,0.0), Point(1.0,0.0), Point(0.0,1.0))

// Catch exception thrown by trying to call method from unsupported shape
try{    
    println("\nTest method call from unsupported shape:")
    triangle.newMethod()
} catch {
    case dns: NewMethodNotSupported => println(dns); System.exit(-1)
    case unknown => println("Uknown exception " + unknown); System.exit(-1)
}

I went with a solution along these lines:

//---------- Classes without needed behavior
case class Point(x: Double, y: Double)
trait Shape {}
case class Circle(center: Point, radius: Double) extends Shape {}
case class Rectangle(lowerLeft: Point, upperRight: Point) extends Shape {}


val circle = Circle(Point(1.0, 2.0), 5.0)
val rectangle = Rectangle(Point(-2.0, -1.0), Point(4.0, 5.0))


//----------- Support for new behavior I want to add

// Create exception to handle non supported subclasses
case class NewMethodNotSupported(a: Any)
    extends RuntimeException(a.toString + ".newMethod() not supported")

class NewBehavior(shape: Shape) {
    def newMethod() = shape match {
        case c: Circle => doMethod(c)
        case r: Rectangle => doMethod(r)
        case _ => throw NewMethodNotSupported(shape)
    }
    private
    def doMethod(s: Shape) = println(s) // print to standard out.
}

object NewBehavior {
    // invoked by the compiler
    implicit def shapeToNewBehavior(s: Shape) = new NewBehavior(s)
}

// bring the implicit method in scope
import NewBehavior._
// --------- End of new behavior support        


// Test behavior support:
println("Test that new behavior is added:")
circle.newMethod()
rectangle.newMethod()

// Create a non supported shape class
case class Triangle(vertex1: Point,
        vertex2: Point, vertex3: Point) extends Shape {}

val triangle = Triangle(Point(-1.0,0.0), Point(1.0,0.0), Point(0.0,1.0))

// Catch exception thrown by trying to call method from unsupported shape
try{    
    println("\nTest method call from unsupported shape:")
    triangle.newMethod()
} catch {
    case dns: NewMethodNotSupported => println(dns); System.exit(-1)
    case unknown => println("Uknown exception " + unknown); System.exit(-1)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文