Clojure 中 BigInt 与 BigInteger 的用例 [英] use-cases for BigInt versus BigInteger in Clojure

查看:17
本文介绍了Clojure 中 BigInt 与 BigInteger 的用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关何时在 Clojure 中使用 Clojure BigInt 与 Java BigInteger 的指导.两者都工作得很好,我假设使用 BigInt 的主要原因是利用像 += 这样的运算符,它们必须通过 Java 实例访问例如方法 .add.equals.但是很少有运算符,例如 isProbablePrime,我只能从 BigInteger 访问.

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.

从 BigInt 转换到 BigInteger 似乎很容易,反之亦然,但两者的存在使我不清楚用例.我的下意识反应只是在没有明确标准的情况下坚持使用 BigInteger,因为一些建议的用法似乎不起作用.来自 clojuredocs 此处:

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)

推荐答案

在 C. Emerick 等人的Clojure Programming"中.al.,第 428 页,有一个侧边栏主题,当 Java 已经在 BigInteger 中提供了一个类时,为什么 Clojure 有自己的 BigInt 类?"

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?"

他们注意到比 Java 的 BigInteger 更喜欢 BigInt 的两个原因.第一,后者的.hashCode实现与Long不一致(每种类型表达的相同数字给出不同的hash值).在比较等效值时,这通常不是您想要的,例如哈希映射.

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.

另一个原因是 BigInt 被优化为在可能的情况下使用原始类型,因此在许多情况下性能应该更好.

The other reason is that BigInts are optimized to use primitive types when possible, so performance should be better for many cases.

除非您有充分的理由不使用,否则我会使用 Clojure 的数字类型(您对 .isProbablePrime 的使用表明您可能有充分的理由).

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

这篇关于Clojure 中 BigInt 与 BigInteger 的用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆