Numbers API has no abs function

221 views
Skip to first unread message

Paul Drummond

unread,
Oct 29, 2008, 9:20:42 AM10/29/08
to Clojure
Is there reason why abs is not part of the Numbers interface?

Currently I need to differentiate between binary decimals and
BigDecimals:

(. java.lang.Math (abs -1))
1
(. -1M (abs))
1M

And if I accidentally use BigDecimal in the wrong place I get an NPE:

(. java.lang.Math (abs -1M))
java.lang.NullPointerException (NO_SOURCE_FILE:0)

Would be nice to be able to use:

(abs -1.0)
1
(abs 1.0M)
1M

and get the overloading provided by the Numbers interface.

Cheers,
Paul Drummond

konrad...@laposte.net

unread,
Oct 29, 2008, 9:46:17 AM10/29/08
to Clojure
On Oct 29, 2:20 pm, Paul Drummond
<paul.drummond.webm...@googlemail.com> wrote:

> Is there reason why abs is not part of the Numbers interface?

I don't know, but...

> Would be nice to be able to use:
>
> (abs -1.0)
> 1
> (abs 1.0M)
> 1M

How about this:

(defn abs [x]
(if (< x 0) (- x) x))

This does what you requested:

user=> (abs -1.0)
1.0
user=> (abs 1.0M)
1.0M

Konrad.

Paul Drummond

unread,
Oct 29, 2008, 10:31:54 AM10/29/08
to Clojure
On Oct 29, 1:46 pm, "konrad.hin...@laposte.net"
<konrad.hin...@laposte.net> wrote:
> How about this:
>
> (defn abs [x]
> (if (< x 0) (- x) x))

I will use that - I should have considered making my own version
rather than messing around with BigDecimal.abs(). Thanks!

Reply all
Reply to author
Forward
0 new messages