简体   繁体   English

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

[英]How to pass list as a parameter to a clojure function

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

Clojure: 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: 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. 打印出15。

You might want to look at the great answers to the question on calling clojure from Java 您可能想看看有关从Java调用clojure的问题的绝佳答案

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. 列表没有什么特别的:可以使用相同的方式将任何Java对象作为参数传递给Clojure函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM