I'm looking for guidance on when to use Clojure BigInt versus Java BigInteger in Clojure. Both work just fine, and I am assuming that the main reason to use BigInt is to take advantage of operators like + and =, which have to be accessed via the Java instance methods .add and .equals, for instance. But there are few operators, such as isProbablePrime, that I can only access from BigInteger.
It seems pretty easy to shift from BigInt to BigInteger or vice versa, but the presence of both makes the use-cases unclear for me. My knee-jerk reaction is just to stick with BigInteger in the absence of clear criteria since some of the suggested usages seem not to work. From clojuredocs here:
user=> (def x (bigint 97))
user=> (.isProbablePrime x 1)
IllegalArgumentException No matching method found: isProbablePrime for class
clojure.lang.BigInt clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:53)
In "Clojure Programming" by C. Emerick et. al., p.428, there is a sidebar topic, "Why Does Clojure Have Its Own BigInt Class When Java Already Provides One in BigInteger?"
They note two reasons to prefer BigInt to Java's BigInteger. First, the latter's .hashCode implementation is inconsistent with that of Long (the same number expressed in each type gives a different hash value). This is generally not what you want when comparing equivalent values in e.g. hash maps.
The other reason is that BigInts are optimized to use primitive types when possible, so performance should be better for many cases.
I would use Clojure's numeric types unless you have a good reason not to (your use of .isProbablePrime suggests you might have a good enough reason).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With