如何将列表作为参数传递给clojure函数

时间:2011-10-05 09:07:22

标签: clojure

如何将list(collection)作为参数传递给clojure函数,这个clojure由java代码调用。

2 个答案:

答案 0 :(得分:1)

Clojure的:

(ns utils ; Sets the namespace to utils
   (:gen-class :name Utils ; The keyword :gen-class declares that
                           ; I want this compiled as a class. The
                           ; :name declares the name (and the package)
                           ; of the class I want created. 
               :methods [#^{:static true} [sum [java.util.Collection] long]]))
                           ; In the vector following :methods I've declared
                           ; the methods I want to have available in the
                           ; generated class. So I want the function 'sum'
                           ; which takes a 'java.util.Collection' as an
                           ; argument and returns a value of type 'long'.
                           ; The metadata declaration '#^{:static true}
                           ; signals that I want this method to be declared
                           ; static.

; The Clojure function. Takes a collection and
; sums the values in the collection using 'reduce'
; and '+'.
(defn sum [coll] (reduce + coll))

; The wrapper function that is available to Java.
; Just calls 'sum'.
(defn -sum [coll] (sum coll))

爪哇:

public class CalculateSum {
  public static void main(String[] args) {
    java.util.List<Integer> xs = new java.util.ArrayList<Integer>();
    xs.add(10);
    xs.add(5);
    System.out.println(Utils.sum(xs));
  }
}

这打印出15。

答案 1 :(得分:0)

您可能希望在calling clojure from Java

上查看问题的优秀答案

列表没有什么特别之处:任何Java对象都可以以相同的方式作为参数传递给Clojure函数。