Clojure与Java互操作: Java.math.BigInteger

3

我有一段Clojure代码,输出的结果是BigInteger。

(ns com.domain.tiny
  (:gen-class
    :name com.domain.tiny
    :methods [#^{:static true} [binomial [int int] java.math.BigInteger]]))

(defn binomial
  "Calculate the binomial coefficient."
  [n k]
  (let [a (inc n)]
    (loop [b 1
           c 1]
      (if (> b k)
        c
        (recur (inc b) (* (/ (- a b) b) c))))))

(defn -binomial
  "A Java-callable wrapper around the 'binomial' function."
  [n k]
  (binomial n k))

(defn -main []
  (println (str "(binomial 5 3): " (binomial 5 3)))
  (println (str "(binomial 10042 111): " (binomial 10042 111)))
)

如果作为独立程序运行,我可以轻松地获得结果:

(binomial 5 3): 10
(binomial 10042 111): 
4906838957506814494663377752836616342 ...
48178314846156008309671682804824359157818666487159757179543983405334334410427200

我可以使用lein uberjar命令生成jar文件。尝试从Java中使用它时,我编写了以下代码。

import com.domain.tiny;
import java.math.BigInteger;
public class Hello
{
    public static void main(String[] args) {
        BigInteger res = tiny.binomial(5, 3);
        System.out.println("(binomial 5 3): " + res);
        res = tiny.binomial(10042, 111);
        System.out.println("(binomial 10042, 111): " + res);
    }
}

很不幸,我遇到了异常。

Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast 
    to java.math.BigInteger
at com.domain.tiny.binomial(Unknown Source)
at Hello.main(Hello.java:11)

我该如何在Clojure和Java中进行Java.Math.BigInteger的互操作?我可以使用:methods [#^{:static true} [binomial [int int] double]]))double res = tiny.binomial(10042, 111);但不适用于BigInteger。

以下是我获取jar包并执行java的步骤:

lein new com.domain.tiny
copy the tiny.clj in com.domain
lein deps
lein uberjar
javac -cp .:com.domain.tiny-1.0.0-SNAPSHOT-standalone.jar Hello.java
java -cp .:com.domain.tiny-1.0.0-SNAPSHOT-standalone.jar Hello

以下clojure代码是从Calling clojure from java复制而来:


2
Clojure非常酷。 - Sotirios Delimanolis
你尝试过返回一个java.math.BigInteger吗?(java.math.BigInteger. "123123123") - guilespi
1个回答

0

返回值应该是clojure.lang.BigInt。

Clojure代码

:methods [#^{:static true} [binomial [int int] clojure.lang.BigInt]]))
(defn binomial
  "Calculate the binomial coefficient."
  [n k]
  (let [a (inc n)]
    (loop [b 1
           c 1]
      (if (> b k)
        (bigint c) ;; <-- Without this code 
                   ;; java.lang.ClassCastException: 
                   ;; java.lang.Long cannot be cast to clojure.lang.BigInt occurs
        (recur (inc b) (* (/ (- a b) b) c))))))

Java 代码

import clojure.lang.BigInt;
...
BigInt res = tiny.binomial(10042, 111);
System.out.println("(binomial 10042, 111): " + res.toString());

结果

java -cp .:com.domain.tiny-1.0.0-SNAPSHOT-standalone.jar Hello
>>> 
(binomial 5 3): 10
(binomial 10042 111): 49068389575068144946 … 27200

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接