From: Jim Weirich Date: 2005-05-27T12:38:35+09:00 Subject: Re: A different perspective on Ruby. On Thursday 26 May 2005 04:11 pm, Glenn Parker wrote: > I can't think of any unary > mathematical operations that are naturally postfix, Factorial ! > One justification for sqrt(5) would be that "sqrt", works on more than > one class of objects (Fixnum, Bignum, Rational, etc). �So does "abs" for > that matter, and I'm not crazy about 5.abs. �As a method, sqrt would > have to be defined in every applicable class, either with new code or as > an included module. �This spreads the definition out, which complicates > maintainence. Actually, I think you have this backwards. It would be much more convenient to have sqrt as a member function in order to implement it differently in different classes. Numeric could hold the standard definition, but if a subclass needed to redefine it, it could do so with little effort. Look at the code in complex.rb to see how it handles enhancing sqrt to handle complex numbers: alias sqrt! sqrt # ... def sqrt(z) if Complex.generic?(z) if z >= 0 sqrt!(z) else Complex(0,sqrt!(-z)) end else if z.image < 0 sqrt(z.conjugate).conjugate else r = z.abs x = z.real Complex( sqrt!((r+x)/2), sqrt!((r-x)/2) ) end end end If sqrt were a member function, the generic test could be completely avoided. Although the original sqrt would still have to be enhanced to handle negative values, it would only have to test for < 0, rather than the rather fragile test for Integer, Float and Rational. -- -- Jim Weirich jim@weirichhouse.org http://onestepback.org ----------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)