如何将列表作为参数传递给Clojure函数 [英] How to pass list as a parameter to a clojure function
本文介绍了如何将列表作为参数传递给Clojure函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将list(collection)作为参数传递给clojure函数,该clojure由Java代码调用.
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));
}
}
这将打印出15.
这篇关于如何将列表作为参数传递给Clojure函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文