2011-07-09 56 views

回答

7

我會建議使用一些其他的運營商(比方說\)爲您的Rational文字,如/已經在所有數字類型上定義爲除法操作。

scala> case class Rational(num: Int, den: Int) { 
    | override def toString = num + " \\ " + den 
    | } 
defined class Rational 

scala> implicit def rationalLiteral(num: Int) = new { 
    | def \(den: Int) = Rational(num, den) 
    | } 
rationalLiteral: (num: Int)java.lang.Object{def \(den: Int): Rational} 

scala> val oneHalf = 1 \ 2 
oneHalf: Rational = 1 \ 2 
+1

'÷'('\ u00f7')怎麼樣?否則\使2看起來像是超過1。 – huynhjl

5

我要偷MissingFaktor的答案,但稍微改變它。

case class Rational(num: Int, den: Int) { 
    def /(d2: Int) = Rational(num, den * d2)  
} 

object Rational { 
    implicit def rationalWhole(num: Int) = new { 
    def r = Rational(num, 1) 
    } 
} 

然後,你可以做這樣的事情,我認爲這是比用反斜槓更好一點,更一致的,因爲你會想反正定義有理所有常見的數值運算符:

scala> 1.r/2 
res0: Rational = Rational(1,2) 
相關問題