Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use-cases for BigInt versus BigInteger in Clojure

Tags:

clojure

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)
like image 919
Reb.Cabin Avatar asked Aug 02 '13 16:08

Reb.Cabin


1 Answers

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

like image 119
JohnJ Avatar answered Oct 20 '22 04:10

JohnJ