7

For example see the following

http://www.artima.com/pins1ed/functional-objects.html

The code uses

val oneHalf = new Rational(1, 2) 

Is there a way to do something like

val oneHalf: Rational = 1/2
1
  • I know your example is just pseudocode but I like it! In order to make that work, one would overload the / operator on Ints to return Rational objects instead of Ints. That would be interesting! Commented Jul 9, 2011 at 3:05

2 Answers 2

7

I would recommend using some other operator (say \) for your Rational literal, as / is already defined on all numeric types as a division operation.

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
Sign up to request clarification or add additional context in comments.

1 Comment

How about ÷ ('\u00f7')? Otherwise \ makes it seems like 2 is over 1.
5

I'm going to steal MissingFaktor's answer, but change it up slightly.

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)
  }
}

Then you can do something like this, which I think is a little nicer than using the backslash, and more consistent since you'll want to define all the usual numeric operators on Rational anyway:

scala> 1.r / 2
res0: Rational = Rational(1,2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.