scala中的Rational代码

scala中的Rational代码,scala,Scala,/*想阅读计算((1/2)+(2/3))的rational代码吗。我找到了这个密码,但我有一个问题*/ object Rationals { val x= new Rational(1, 2) // 1/2 x.numer // * x.denom // ** /* * and ** are my questions. why I have to use them? */ val y = new Rational(2, 3) //

/*想阅读计算((1/2)+(2/3))的rational代码吗。我找到了这个密码,但我有一个问题*/

object Rationals
{
     val x= new Rational(1, 2) // 1/2

     x.numer // *
     x.denom // **
       /*  * and ** are my questions. why I have to use them?   */

     val y = new Rational(2, 3) // 2/3
     x.add(y)

      /* my result most be equal to 7/6 */
}


class Rational (x : Int, y : Int)
{
     def numer= x
     def denom= y

     def add (that : Rational) =
     new Rational (
     numer * that.denom + that.numer * denom,   /* 1*3 + 2*2 */
     denom * that.denom) /* 2*2 */

    override def toString = numer + "/" + denom   /* 7/6 */

 }
台词:

     x.numer // *
     x.denom // **

你什么都没做。它们正在被计算,但没有被使用;而且它们没有副作用。

如果你在Scala使用理性主义(以及类似的理论),那么我建议你使用Spire,而不是尝试重新发明轮子: