Variadic Functions in Clojure

Here’s a function that will take an arbitrary number of ints as arguments.

(defn sum [& nums]
  (println nums " ")
  (let [total (reduce + nums)]
    (println total)))

(defn -main []
  ; Variadic functions can be called in the usual way with individual arguments.
  (sum 1 2)
  (sum 1 2 3)
  ; If you already have multiple args in a collection,
  ; apply them to a variadic function using `apply`.
  (let [nums [1 2 3 4]]
    (apply sum nums)))

(-main)

To run the program, you can use lein run, assuming you have Leiningen installed and set up:

$ lein run

Or you can compile and run using Clojure from the command line. Save the code in a file named variadic_functions.clj and execute:

$ clojure variadic_functions.clj

Here’s what you should expect as the output:

[1 2] 3
[1 2 3] 6
[1 2 3 4] 10

Now that we can run and understand basic variadic functions in Clojure, let’s learn more about the language.