Saturday, May 21, 2011

Division in Clojure

Clojure includes a Ratio type which we can access using a ratio literal like this
(+ 2/3 3/4)
=> 17/12


You need to be careful because the '/' operator will return a ratio if the result is not a whole number (most languages return an integer)
Ruby: 16/7
=> 2
Clojure: (/ 16 7)
=> 16/7


The % sign means something different (the first argument to an anonymous function actually) rather than being a modulus operator
(% 16 7)
java.lang.IllegalStateException: arg literal not in #()


If you want to do integer division or get the mod, you need to use the quot (quotient) and rem (remainder) functions
(quot 16 7)
=> 2

(rem 16 6)
=> 4


You can also use decimal numbers to do decimal division
(/ 16.0 7)
=> 2.2857142857142856

No comments:

Post a Comment