Here's a quick note of making Groovy to support complex numbers:
1. override number operations via metaclass:
Number.metaClass.plus = { n ->
if(n instanceof Imaginary) {
return new Complex(r:delegate, i:n.v)
}
}
2. define class Complex to hold real, r, and imaginary, i, parts
class Complex {
def r
def i
String toString() {
"$r + ${i}i"
}
}
3. create class Imaginary to be a wrapper class (I borrow this idea from Scala's implicit converter).
class Imaginary {
def v
}
4. define i as a global closure. It would be in DefaultGroovyMethods, actually.
def i = { v ->
new Imaginary(v:v)
}
Then when you write:
def b = 2 + i(2.4)
println b
println b.class
This prints "2 + 2.4i" and the type of b is class Complex.
1. override number operations via metaclass:
Number.metaClass.plus = { n ->
if(n instanceof Imaginary) {
return new Complex(r:delegate, i:n.v)
}
}
2. define class Complex to hold real, r, and imaginary, i, parts
class Complex {
def r
def i
String toString() {
"$r + ${i}i"
}
}
3. create class Imaginary to be a wrapper class (I borrow this idea from Scala's implicit converter).
class Imaginary {
def v
}
4. define i as a global closure. It would be in DefaultGroovyMethods, actually.
def i = { v ->
new Imaginary(v:v)
}
Then when you write:
def b = 2 + i(2.4)
println b
println b.class
This prints "2 + 2.4i" and the type of b is class Complex.