Arithmetic/Complex: Difference between revisions

→‎{{header|Groovy}}: minor rewrite/reorg
m ({{out}})
(→‎{{header|Groovy}}: minor rewrite/reorg)
Line 1,510:
=={{header|Groovy}}==
Groovy does not provide any built-in facility for complex arithmetic. However, it does support arithmetic operator overloading. Thus it is not too hard to build a fairly robust, complete, and intuitive complex number class, such as the following:
<lang groovy>importclass org.codehaus.groovy.runtime.DefaultGroovyMethods;Complex {
 
class Complex {
final Number real, imag
 
Line 1,611 ⟶ 1,609:
: realPart + (imag > 0 ? " + " : " - ") + imagPart
}
}</lang>
}
 
The following ''ComplexCategory'' class allows for modification of regular ''Number'' behavior when interacting with ''Complex''.
<lang groovy>import org.codehaus.groovy.runtime.DefaultGroovyMethods
 
class ComplexCategory {
Line 1,628 ⟶ 1,629:
}
}</lang>
The ComplexCategory class allows for modification of regular Number behavior when interacting with Complex. Notice also that this solution takes liberal advantage of Groovy's full Unicode support, including support for non-English alphabets used in identifiers.
 
Test Program (mixes the ComplexCategory methods into the Number class):
Anonymous user