Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: What does [_] do in a Functions Argument List?

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))
like image 815
David Williams Avatar asked Apr 15 '13 16:04

David Williams


People also ask

What does fn mean in Clojure?

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.

How do you return a function in Clojure?

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 .

What is let in Clojure?

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.


1 Answers

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.

like image 65
harpo Avatar answered Sep 24 '22 07:09

harpo