Search code examples
clojureswitch-statementcaseindexoutofboundsexception

Compact way in Clojure to print a variable number of command line arguments?


I'm a newbie to Clojure. I think I'm trying to solve this procedurally and there must be a better (more functional) way to do this in Clojure...

The -main function can receive a variable number of 'args'. I would like to print them out but avoid an IndexOutOfBoundsException. I thought I could mimic Java and use a case fall-through to minimize the code involved, but that didn't work:

(defn -main [& args]
  (println "There are" (str (count args)) "input arguments.")
  (println "Here are args:" (str args))
  (let [x (count args)]
    (case x
      (> x 0) (do
          (print "Here is the first arg: ")
          (println (nth args 0)))
      (> x 1) (do
          (print "Here is the 2nd arg: ")
          (println (nth args 1)))
      (> x 2) (do
          (print "Here is the 3rd arg: ")
          (println (nth args 2))))))

Solution

  • (doseq [[n arg] (map-indexed vector arguments)]
      (println (str "Here is the argument #" (inc n) ": " (pr-str arg))))
    

    map-indexes is like map but adds index number in the beginning. So it goes item by item through arguments, packs index and item into a vector and by destructruing index number and item are mapped to [n arg].

    Since clojure begins counting from 0, you use (inc n) to begin counting from 1. pr-str is pretty print string. The str joins all string components together.