Question

How can I convert a long int to a rational in Clojure?

That does not work:

user> (class (/ 5 1))
java.long.Long
Was it helpful?

Solution 2

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

OTHER TIPS

You don't need to explicitly convert a long into a rational.

Clojure will convert

  • a rational (clojure.lang.Ratio) into a long (java.lang.Long) when it can: when the denominator is or can be made to be 1;
  • longs or other ints into a rational when it must: when a division cannot be resolved to a denominator of 1.

Thus

(type (/ 4 2)) ; java.lang.Long

(type (/ 4 3)) ; clojure.lang.Ratio

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top