diff --git a/Koans/src/test/scala/org/functionalkoans/forscala/Flight03.scala b/Koans/src/test/scala/org/functionalkoans/forscala/Flight03.scala index e12a6fe..34d10d0 100755 --- a/Koans/src/test/scala/org/functionalkoans/forscala/Flight03.scala +++ b/Koans/src/test/scala/org/functionalkoans/forscala/Flight03.scala @@ -4,7 +4,7 @@ import support.BlankValues._ import support.KoanSuite class Flight03 extends KoanSuite with ShouldMatchers { - + // Flight 03 exercise - uncomment the tests below, and then define a class // called ComplexNum that: // 1. Has class parameters real and imaginary @@ -21,10 +21,25 @@ class Flight03 extends KoanSuite with ShouldMatchers { // The tests below should exercise all of these requirements although they // are far from exhaustive - // class ... + class ComplexNum( val real: Double, val imaginary: Double ) { + def this( real: Double ) { this( real, 0d) } + + override def toString = this.imaginary match { + case x: Double if(x < 0) => real + " - " + math.abs(imaginary) + "i" + case x: Double => real + " + " + imaginary + "i" + } + + def +( other: ComplexNum ) : ComplexNum = { + new ComplexNum( this.real + other.real, this.imaginary + other.imaginary ) + } + + def +( num: Double ) = new ComplexNum( this.real + num, this.imaginary ) + } + + implicit def double2ComplexNum( double: Double ) = new ComplexNum( double ) // UNCOMMENT BELOW - /*test ("Create a new Complex number and check the values for the real/imaginary parts") { + test ("Create a new Complex number and check the values for the real/imaginary parts") { val complex = new ComplexNum(4, 2) complex.real should be (4) @@ -67,32 +82,31 @@ class Flight03 extends KoanSuite with ShouldMatchers { complex.real should be (12) complex.imaginary should be (3.2) - } - */ + } // Extra credit - numbers with a negative imaginary part should be output // as 6.0 - 5.0i instead of 6.0 + -5.0i - if you have time, write a new test // for this outcome, and then adapt the toString in the class to work correctly // Hint: scala.math.abs will give the absolute value of a double - + // UNCOMMENT BELOW - /*test ("Format for negative imaginary part should be R.R - I.Ii") { + test ("Format for negative imaginary part should be R.R - I.Ii") { val complex = new ComplexNum(5, -6) val complex2 = new ComplexNum(5.5, -6.6) complex.toString should be ("5.0 - 6.0i") complex2.toString should be ("5.5 - 6.6i") - }*/ + } // Extra extra credit - adding a double to a complex works, but adding a complex // to a double does not. If you add an implicit conversion you can make this work // if you have time, write a test, and add an implicit to make it work // UNCOMMENT BELOW - /*test ("Add a complex to a double") { + test ("Add a complex to a double") { val complex = 5.6 + new ComplexNum(3.4, 4.5) complex.real should be (9) complex.imaginary should be (4.5) - }*/ + } }