Instantly share code, notes, and snippets.

# teroxik/ComplexNumber Created Apr 9, 2013

What would you like to do?
Complex number implementation in Scala with various features of Scala language as coded at Czech Scala Enthusiasts' Scala coding dojo on Apr 9, 2013
 package com.czechscala.blank class ComplexNumber private(val x: Int, val y: Int) { override def toString() = s"\$x + \${y}i" override def equals(c: Any) = c match { case x : ComplexNumber => x.x == this.x && x.y == y case _ => false } override def hashCode() = 31 + 23 * this.x + 17 * this.y def add(c: ComplexNumber) = new ComplexNumber(this.x+c.x, this.y +c.y) def +(c: ComplexNumber) = add(c) def -(c: ComplexNumber) = add(ComplexNumber(-c.x,-c.y)) def absoluteValue() : Int = math.sqrt((x*x) - (y*y)).toInt def multiply(c: ComplexNumber) = ComplexNumber(x*c.x - y*c.y , x*c.y + y*c.x) def *(c: ComplexNumber) = multiply(c) def transform(f: ComplexNumber => ComplexNumber) = f(this) } object ComplexNumber { val i = ComplexNumber(0,1) def apply(x: Int, y: Int) = new ComplexNumber(x,y) def apply(abs: Int, alpha: Double) = new ComplexNumber((math.cos(alpha)*abs).toInt,(math.sin(alpha)*abs).toInt); implicit def intToComplex(x: Int) = new ComplexNumber(x,0) }
 package com.czechscala.blank import org.scalatest.FunSuite import ComplexNumber.{i,intToComplex} class ComplexNumberTest extends FunSuite { test("complex number is set") { val c = ComplexNumber(4,5) assert(c.x === 4) assert(c.y === 5) } test("complex number to string") { val c = ComplexNumber(20, 10) assert(c.toString()==="20 + 10i") } test("complex number count") { val c1 = ComplexNumber(12, 31) val c2 = ComplexNumber(1, -1) assert(c1 + c2 === ComplexNumber(13, 30)) } test("numbers are equal"){ val c1 = ComplexNumber(12, 31) val c2 = ComplexNumber(12, 31) assert(c1 === c2) } test("numbers aren't equal"){ val c1 = ComplexNumber(12, 31) val c2 = ComplexNumber(12, -2) assert(c1 != c2) } test("number hash code"){ val c = ComplexNumber(1, 1) assert(c.## === 71) } test("get absolute value"){ val c = ComplexNumber(5, 3) assert(c.absoluteValue() === 4) } test("multiplication test"){ val c1 = ComplexNumber(5, 5) val c2 = ComplexNumber(5, -5) assert(c1 * c2 === ComplexNumber(50,0)) } test("dsl complex number test"){ val c1 = 1 + 3*i assert(c1 === ComplexNumber(1,3)) } test("list of complex numbers"){ val c = 2 + 2*i val c1 = c.transform(n => n*i) assert(c1*c === -8 + 0*i) } test("list of complex numbers 2"){ val c = 2 + 2*i val c1 = c.transform((n: ComplexNumber) => {n * (-1 +0*i)}) assert(c1 === -2 -2*i) } }