Hello everyone

I had a go at adding support for complex numbers, it's at:
https://github.com/andrea-chiavazza/clojure/tree/complex

Some repl usage examples:

user=> (/ (complex 73 13) (complex 15 25))
#<Complex (142/85 -163/85i)>

user=> (/ (complex 73 13) (complex 15.0 25.0))
#<Complex (1.6705882352941177 -1.9176470588235295i)>

user=> (+ (complex 13 34) (complex 29 -34))
42

user=> (require 'clojure.math)

user=> (clojure.math/abs (complex -14.94 21))
25.772147756832375

user=> (clojure.math/sqrt -3)
#<Complex (0 +1.7320508075688772i)>

user=> (clojure.math/sqrt 2)
1.4142135623730951

user=> (clojure.math/sqrt (complex 2 3))
#<Complex (1.6741492280355401 +0.895977476129838i)>

user=> (= (complex 12 34) (complex 12 34.0))
false
user=> (== (complex 12 34) (complex 12 34.0))
true

I'm still not sure why #<Complex comes up, while #<Ratio doesn't with 
similar operations.
What also worries me a bit is that I changed a bunch of methods in 
Numbers.java from accepting Object to being overloaded to accept Number and 
Complex.

For example, this:
static public Number add(Object x, Object y){
return ops(x).combine(ops(y)).add((Number)x, (Number)y);
}

Has become:
static public Number add(Number x, Number y){
return ops(x).combine(ops(y)).add(x, y);
}

So that I could overload with this:
static public Object add(Complex x, Complex y) {
Number r = add(x.real, y.real);
Number im = add(x.imaginary, y.imaginary);
if (isZero(im))
return r;
else
return new Complex(r, im);
}

A consequence is that this test:
  (is (thrown? ClassCastException (+ "ab" "cd"))) )    ; no string 
concatenation
Has become:
  (is (thrown? IllegalArgumentException (+ "ab" "cd"))) )    ; no string 
concatenation

I thought that overloading would be nicer and would avoid having to check 
for the class of the Object.
On the other hand all methods seem to accept an Object and then cast to 
Number rather than just accepting a Number, so there might be a good reason 
for that.
Could somebody please enlighten me on this so that I can do it the right 
way ?

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to