1

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))))))

2 Answers 2

3
(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.

Sign up to request clarification or add additional context in comments.

Comments

0

there is also a handy formatting facility in clojure's core library: cl-format, which is the port of common lisp's format syntax. It includes a nice way to print out collections:

(require '[clojure.pprint :refer [cl-format]])

(let [args [:a :b :c :d]]
  (cl-format true "~{here is the ~:r arg: ~a~%~}"
             (interleave (rest (range)) args)))

;; here is the first arg: :a
;; here is the second arg: :b
;; here is the third arg: :c
;; here is the fourth arg: :d

some more information about what format can do is here

2 Comments

Can the cl-format library handle a variadic function with a variable number of parameters instead of a set vector?
sure, there is no difference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.