Chris@44: Chris@44: module complex; Chris@44: Chris@46: import java.lang: ClassCastException; Chris@46: Chris@71: class Cplx(double real, double imag) Chris@44: int getReal() Chris@44: real, Chris@44: int getImag() Chris@44: imag, Chris@53: double getMagnitude() Chris@53: sqrt (real * real + imag * imag), Chris@53: double getAngle() Chris@53: Math#atan2(imag, real), Chris@44: String toString() Chris@48: if real == int real and imag == int imag then Chris@48: if imag < 0 then Chris@48: " \(int real) - \(int (-imag))i" Chris@48: else Chris@48: " \(int real) + \(int imag)i" Chris@48: fi Chris@48: else Chris@48: if imag < 0 then Chris@48: " \(real) - \((-imag))i" Chris@48: else Chris@48: " \(real) + \(imag)i" Chris@48: fi Chris@48: fi, Chris@46: int hashCode() Chris@46: Double#valueOf(real)#hashCode() + Double#valueOf(imag)#hashCode(), Chris@46: boolean equals(Object other) Chris@46: try Chris@71: c = other unsafely_as ~Cplx; Chris@46: c#getReal() == real and c#getImag() == imag Chris@46: catch ClassCastException: Chris@46: false Chris@46: yrt, Chris@44: end; Chris@44: Chris@71: typedef opaque cplx = ~Cplx; Chris@44: Chris@71: real c1 is ~Cplx -> number = Chris@46: c1#getReal(); Chris@46: Chris@71: imaginary c1 is ~Cplx -> number = Chris@46: c1#getImag(); Chris@46: Chris@71: complex re im is number -> number -> ~Cplx = Chris@71: new Cplx(re, im); Chris@46: Chris@71: magnitude c is ~Cplx -> number = Chris@53: c#getMagnitude(); Chris@53: Chris@71: angle c is ~Cplx -> number = Chris@53: c#getAngle(); Chris@53: Chris@71: add c1 c2 is ~Cplx -> ~Cplx -> ~Cplx = Chris@46: complex (real c1 + real c2) (imaginary c1 + imaginary c2); Chris@46: Chris@71: scale r c is number -> ~Cplx -> ~Cplx = Chris@46: complex (r * real c) (r * imaginary c); Chris@44: Chris@44: { Chris@46: real, Chris@46: imaginary, Chris@46: complex, Chris@53: magnitude, Chris@53: angle, Chris@46: add, Chris@46: scale, Chris@44: } as { Chris@46: real is cplx -> number, Chris@46: imaginary is cplx -> number, Chris@46: complex is number -> number -> cplx, Chris@53: magnitude is cplx -> number, Chris@53: angle is cplx -> number, Chris@46: add is cplx -> cplx -> cplx, Chris@46: scale is number -> cplx -> cplx, Chris@44: } Chris@44: