Reputation: 310792
How can the absolute number of a value be calculated in Clojure?
(abs 1) => 1
(abs -1) => 1
(abs 0) => 0
Upvotes: 48
Views: 26551
Reputation: 6956
As of Clojure 1.11, it is simply (abs -1)
in both Clojure and Clojurescript.
In versions before, for double, float, long and int you can use the java.lang.Math method abs (Math/abs -1)
Take care it won't work for decimals, ratio's, bigint(eger)s and other Clojure numeric types. The official clojure contrib math library that tries guarantee working correctly with all of these is clojure.math.numeric-tower
Upvotes: 58
Reputation: 2798
abs
is now available in the core clojure library since Clojure 1.11
release.
Docs for abs
https://clojure.github.io/clojure/branch-master/clojure.core-api.html#clojure.core/abs
Usage: (abs a)
Returns the absolute value of a.
If a is Long/MIN_VALUE => Long/MIN_VALUE
If a is a double and zero => +0.0
If a is a double and ##Inf or ##-Inf => ##Inf
If a is a double and ##NaN => ##NaN
Added in Clojure version 1.11
Upvotes: 3
Reputation: 310792
The deprecated clojure.contrib.math
provides an abs
function.
The source is:
(defn abs "(abs n) is the absolute value of n" [n]
(cond
(not (number? n)) (throw (IllegalArgumentException.
"abs requires a number"))
(neg? n) (- n)
:else n))
As @NielsK points out in the comments, clojure.math.numeric-tower
is the successor project.
Upvotes: 12