1
(ns utils
   (:gen-class :name Utils
               :methods [#^{:static true} [sum [java.util.Collection] long]]))

(defn sum [coll] (reduce + coll))

(defn -sum [coll] (sum coll))

Please explain this code!

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
vikbehal
  • 1,486
  • 3
  • 21
  • 48
  • 2
    Sure, do you want fries while you wait? Or put slightly less cynically: have you *tried* understanding it? What is your interpretation, where are you stuck? – Joachim Sauer Oct 05 '11 at 12:46
  • This isn't homework by any chance, right? ;) – Matt Oct 05 '11 at 13:02
  • 1
    @Matt it is actually a copy-paste of my original answer here: http://stackoverflow.com/questions/7658954/how-to-pass-list-as-a-parameter-to-a-clojure-function – ponzao Oct 05 '11 at 18:35
  • @Matt '(defn sum [coll] (reduce + coll)) (defn -sum [coll] (sum coll))' In this, first sum function is calculating the sum. 2nd sum function(-sum) is required but why? and both function names have to be same? – vikbehal Oct 07 '11 at 05:31
  • They don't have to be. You can rename the first sum to whatever you please. The -sum definition has to be named like this because of the `:methods ... [sum [java.util...]]` definition – Matt Oct 07 '11 at 08:43

1 Answers1

5

Having not used the Clojure gen-class facilities, my answer might be a little fuzzy:

This will generate the necessary byte-code which is about equivilant to the following Java pseudo code:

class Utils {
  public static long sum(Collection coll) {
    // Here goes the necessary code to call  (sum coll)
    // through the Clojure runtime
  }
}
  • -sum instructs Clojure to generate the Java method.
  • (sum coll) is the call to the first definition of sum, which is just a regular Clojure function definition
Matt
  • 17,290
  • 7
  • 57
  • 71