How can I convert a long int to a rational in Clojure?
That does not work:
user> (class (/ 5 1))
java.long.Long
How can I convert a long int to a rational in Clojure?
That does not work:
user> (class (/ 5 1))
java.long.Long
You don't need to explicitly convert a long into a rational.
Clojure will convert
clojure.lang.Ratio
) into a long (java.lang.Long
) when it can: when the denominator is or can be made to be 1
; 1
. Thus
(type (/ 4 2))
; java.lang.Long
(type (/ 4 3))
; clojure.lang.Ratio
There's rationalize
. But that doesn't do what you want -- it still returns a long if the denominator is a 1. However, if you want this for type testing purposes, the Clojure function rational?
returns true for longs.
If you really want Ratio types, I think you'll have to write it yourself, since the source of rationalize
dives immediately into the underlying Java.
(clojure.lang.Ratio.
(. BigInteger (valueOf 3))
(. BigInteger (valueOf 1)))
; 3/1
Perhaps:
(defn myrationalize
[num]
(if (integer? num)
(clojure.lang.Ratio.
(. BigInteger (valueOf num))
(. BigInteger (valueOf 1)))
(rationalize num)))