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)))