Created
April 10, 2013 07:58
-
-
Save jakubjanecek/5352686 to your computer and use it in GitHub Desktop.
Implementation of complex numbers from Czech Scala Enthusiasts coding dojo held on April 9th 2013
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ComplexNumber private (val x: Int, val y: Int) { | |
def +(c: ComplexNumber) = ComplexNumber(x + c.x, y + c.y) | |
def *(c: ComplexNumber) = ComplexNumber((x * c.x) - (y * c.y), (y * c.x) + (x * c.y)) | |
// higher-order method | |
def transform(f: ComplexNumber => ComplexNumber) = f(this) | |
override def toString = s"$x + ${y}i" | |
override def equals(obj: Any): Boolean = obj match { | |
case c: ComplexNumber => x == c.x && y == c.y | |
case _ => false | |
} | |
override def hashCode(): Int = 31 + (31 * x + 31 * y) | |
} | |
object ComplexNumber { | |
val i = ComplexNumber(0, 1) | |
def apply(x: Int, y: Int) = new ComplexNumber(x, y) | |
implicit def int2Complex(i: Int) = ComplexNumber(i, 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment