How to pass list as a parameter to a clojure function
How to pass list(collection) as a parameter to a clojure function, this clojure 开发者_如何学编程is called by java code.
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))
Java:
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));
}
}
This prints out 15.
You might want to look at the great answers to the question on calling clojure from Java
There's nothing special particularly about a list: any Java object can be passed as a parameter to a Clojure function in the same way.
精彩评论