Why do Clojure rationals use Java `BigInteger`s in preference to Clojure `BigInt`s?

StackOverflow https://stackoverflow.com/questions/23371922

  •  12-07-2023
  •  | 
  •  

Question

Clojure finds it worthwhile to wrap Java BigIntegers in its own BigInt class that uses an ordinary long where that is big enough: thus speeding up markedy arithmetic on small instances of BigInt, at the cost of slowing down slightly arithmetic on big instances.

  • Doesn't the same argument apply to ratios of integers?
  • Why then does Clojure use naked Java BigIntegers for its Ratio type, instead of wrapping them in BigInts?
Was it helpful?

Solution

Ratio predates BigInt.

If I recall correctly, BigInt was introduced so that "asking for a box" (to get arbitrary precision arithmetic) by appending N to (integral) numeric literals would not result in too much of a performance penalty. Tweaking Ratio was probably not a high priority. In fact, I don't recall the subject coming up at all -- and I'm not surprised, Ratio's not really about top arithmetic performance anyway.

Still, perhaps some adventurous programmer will one day rewrite it to use BigInt.

OTHER TIPS

Maybe the major reason for Clojure having it's own BigInt is that hashCode of Java's Long and BigInteger are not congruent. So two numbers representing the same value as Long and as BigInteger are considered different numbers; for example in hash-map comparison.

The source for this answer is here use-cases for BigInt versus BigInteger in Clojure.

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