On Tue, Sep 8, 2009 at 8:18 PM, Timothy Pratley <timothyprat...@gmail.com>wrote:
> > Hi Steve, > > I find the -1, 0, 1 result more useful, but am also wary it hides some > useful information. My preference would be to have the doc-string > changed to what you proposed and keep the neg/pos behaviour > of .compareTo in place. To get -1, 0, 1 requires a 'sign' operator > which is handy to have as a separate function - might be a candidate > for contrib? > > (defn sign > "Returns 1 if x is positive, -1 if x is negative, else 0" > [x] > (cond (pos? x) 1, (neg? x) -1, :else 0)) > (defn sign "Returns 1 if x is positive, -1 if x is negative, else 0" [x] (compare x 0)) If that doesn't work, then compare on numbers is likely to fail for widely-separated numbers due to integer underflow or overflow if the Java compareTo being called does so; compareTo is defined in interface Comparable as returning a Java int, which has 32 bit range; there's a reason it's recommended to implement compareTo using < or >, ==, ?:, and the literal values -1, 0, and 1. The char comparison using subtraction is safe since all differences between 16-bit numbers fit in an int, but this is not true for int, long, or bignum comparison by subtracting and then narrowing to int. For the native Java Integer, Long, and BigInteger types this is highly unlikely to be the case. I'm hoping Clojure's Ratio class's compareTo is also safe. This is assuming the Clojure compare function on numbers works by coercing them along the graph Byte-(Short,Character)-Int-Long-BigInteger-Ratio-BigDecimal, Float-Double-BigDecimal and then using compareTo, as seems likely. (I don't currently have my REPL or the source code handy to check.) --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---