More Clojure Numeric Tests

Here are some more numeric tests.

I went through a Scheme tutorial titled “Teach Yourself Scheme in Fixnum Days”. One page had a nice code excerpt with functions showing all the different kinds of numbers that I found helpful.

  • The set of integers (like 42)
  • Are within the set of rational numbers (like 22/7)
  • Are within the set of real numbers (3.14)
  • Are within the set of complex numbers (like 2+3i)
  • Are within the set of all numbers.

Numbers in Clojure do not quite fit into this hierarchy, since Clojure runs on the JVM. Functions that test for real numbers (like float? or decimal?) return false for integers.

user=> (integer? 42)
true
user=> (rational? 42)
true
;; so integers are rationals
user=> (class 42)
java.lang.Long
user=> (rational? (/ 22 7))
true
user=> (class (/ 22 7))
clojure.lang.Ratio
;; all ratios are rationals, but not vice versa
user=> (ratio? (/ 22 7))
true
user=> (ratio? 42)
false
user=> (rational? 42)
true
user=> (rational? (/ 22 7))
true
user=> (rational? 22/7)
true
user=> (ratio? 22/7)
true
user=> (float? 42)
false
user=> (float? 42.0)
true
;; doesn't fit math hierarchy, these are all Java classes
user=> (class 42.0)
java.lang.Double
user=> (float? 42.3)
true
user=> (rational? 42.3)
false
user=> (number? 42)
true
user=> (number? 42.0)
true
user=> (number? 22/7)
true
user=> (def some-num 33)
#'user/some-num
user=> (number? some-num)
true
user=> (def not-num "Hello")
#'user/not-num
user=> (number? not-num)
false

;; decimal? checks if the arg is a java.math.BigDecimal class
user=> (BigDecimal. "1115.37")
1115.37M
user=> (def bd (BigDecimal. "1115.37"))
#'user/bd
user=> (decimal? bd)
true
user=> (def next-bd (BigDecimal. "1115"))
#'user/next-bd
user=> (decimal? next-bd)
true
user=> next-bd
1115M
user=> (number? bd)
true
user=> (decimal? 42.2)
false
user=> (class bd)
java.math.BigDecimal

 

You’re welcome.

There are 260 words in this article.