I am working through the joy of clojure and am wondering what the _ syntax does in a functions argument vector.
Example:
(def available-processors
(.availableProcessors (Runtime/getRuntime)))
(prn "available processors: " available-processors)
(def pool
(Executors/newFixedThreadPool (+ 2 available-processors)))
(defn dothreads!
[func & {thread-count :threads exec-count :times :or {thread-count 1 exec-count 1}}]
(dotimes [t thread-count]
(.submit pool #(dotimes [_ exec-count] (func)))))
What is the underscore doing in the form:
#(dotimes [_ exec-count] (func))
First Class Functions They can be assigned as values, passed into functions, and returned from functions. It's common to see function definitions in Clojure using defn like (defn foo … ) . However, this is just syntactic sugar for (def foo (fn … )) fn returns a function object.
There isn't a return statement in Clojure. Even if you choose not to execute some code using a flow construct such as if or when , the function will always return something, in these cases nil .
Clojure let is used to define new variables in a local scope. These local variables give names to values. In Clojure, they cannot be re-assigned, so we call them immutable.
I believe that underscore is used in Clojure, by convention, as a placeholder for a required but unused argument. As Keith Bennet puts it:
In Clojure, the underscore is used idiomatically to indicate that the argument it identifies is not subsequently used.
Your example is consistent with this "usage," since the first argument to dotimes, which is an indexer, is not needed, but the binding is required by the form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With