繁体   English   中英

Scala 如何为 Rationals 定义排序

[英]Scala how to define an ordering for Rationals

我必须将 compareRationals 实现为

(a, b) => {

   the body goes here
}

要与分数进行比较,将它们转换为具有相同的分母,然后按分子对两个结果进行排序以确保它们具有相同的分母,需要找出最小公分母,以便我的代码适用于 println(insertionSort2(List (有理数)))并且目前适用于除此之外的所有 println 语句。 我真的需要帮助来定义 compareRationals 所以 println(insertionSort2(List(rationals))) shouldBe List(fourth, third, half)

Object {
     def insertionSort2[A](xs: List[A])(implicit ord: Ordering[A]): List[A] = {
        def insert2(y: A, ys: List[A]): List[A] =
          ys match {
            case List() => y :: List()
            case z :: zs =>
              if (ord.lt(y, z)) y :: z :: zs
              else z :: insert2(y, zs)
          }
    
        xs match {
          case List() => List()
          case y :: ys => insert2(y, insertionSort2(ys))
        }
      }
      class Rational(x: Int, y: Int) {
    
        private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
        private val g = gcd(x, y)
    
        lazy val numer: Int = x / g
        lazy val denom: Int = y / g
      }
      val compareRationals: (Rational, Rational) => Int =
    
    
      implicit val rationalOrder: Ordering[Rational] =
        new Ordering[Rational] {
          def compare(x: Rational, y: Rational): Int = compareRationals(x, y)
        }
      def main(args: Array[String]): Unit = {
        val half = new Rational(1, 2)
        val third = new Rational(1, 3)
        val fourth = new Rational(1, 4)
        val rationals = List(third, half, fourth)
        println(insertionSort2(List(4,2,9,5,8))(Ordering.Int))
        println(insertionSort2(List(4,2,9,5,8)))
        println(insertionSort2(List(rationals)))
      }
}

}

我想这就是你所需要的。

val compareRationals: (Rational, Rational) => Int =
  (x,y) => x.numer * y.denom - y.numer * x.denom

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM