Chapter 5, Exercise 4
THECLAPP wrote: I consider Chapter 5, ex 4 basically make-work. Vim/Emacs automation is your friend. I suppose the P class may come in handy later. Skipping Lisp version, in case you hadn't caught on. :).
But I thought that Scala would be able to do this with type inference. That is, I thought that this should work:
class P[ttype] {
def rint (ss: ttype) = Console.print(ss);
def rintln (ss: ttype) = Console.println(ss);
}
(Actually, I first thought that I should be able to make it "object P[ttype]...", but that got a syntax error.)
When I tried to use the above, Scala couldn't infer the right type of P to instantiate. So I ended up with the following (after adding the *s versions to print a space first). Yuck.
object P {
def rint (ss: String) = Console.print(ss);
def rintln (ss: String) = Console.println(ss);
def rint (ss: Int) = Console.print(ss);
def rintln (ss: Int) = Console.println(ss);
def rint (ss: Long) = Console.print(ss);
def rintln (ss: Long) = Console.println(ss);
def rint (ss: Float) = Console.print(ss);
def rintln (ss: Float) = Console.println(ss);
def rint (ss: Double) = Console.print(ss);
def rintln (ss: Double) = Console.println(ss);
def rint (ss: Boolean) = Console.print(ss);
def rintln (ss: Boolean) = Console.println(ss);
def rints (ss: String) = { Console.print(" "); Console.print(ss); }
def rintlns (ss: String) = { Console.print(" "); Console.println(ss); }
def rints (ss: Int) = { Console.print(" "); Console.print(ss); }
def rintlns (ss: Int) = { Console.print(" "); Console.println(ss); }
def rints (ss: Long) = { Console.print(" "); Console.print(ss); }
def rintlns (ss: Long) = { Console.print(" "); Console.println(ss); }
def rints (ss: Float) = { Console.print(" "); Console.print(ss); }
def rintlns (ss: Float) = { Console.print(" "); Console.println(ss); }
def rints (ss: Double) = { Console.print(" "); Console.print(ss); }
def rintlns (ss: Double) = { Console.print(" "); Console.println(ss); }
def rints (ss: Boolean) = { Console.print(" "); Console.print(ss); }
def rintlns (ss: Boolean) = { Console.print(" "); Console.println(ss); }
}
And here's the driver:
object c5x4u {
def main ( args: Array[String] ) = {
val iv = 12;
val lv = 1200000000000000012L;
val fv = 12.12;
val dv = 12.120000120001200012 ;
val bv = true;
// And try printing them:
P.rintln( "Try iv lv fv dv and bv:" );
P.rints( iv );
P.rints( lv );
P.rints( fv );
P.rints( dv );
P.rints( bv );
P.rintlns( "Did that work?" );
}
}
12:18:50 AM