Clojure 中打印可变数量命令行参数的紧凑方式?

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

我是 Clojure 的新手。我想我正试图在程序上解决这个问题,并且在 Clojure 中必须有更好(更实用)的方法来做到这一点...

-main函数可以接收可变数量的'args'。我想将它们打印出来,但要避免出现 IndexOutOfBoundsException。我以为我可以模仿 Java 并使用 case fall-through 来最小化所涉及的代码,但这没有用:

(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))))))
(doseq [[n arg] (map-indexed vector arguments)]
  (println (str "Here is the argument #" (inc n) ": " (pr-str arg))))

map-indexes 类似于 map 但在开头添加了索引号。 所以它通过参数逐项进行,将索引和项目打包到 vector 中,并通过解构索引号和项目映射到 [n arg].

由于 clojure 从 0 开始计数,因此您使用 (inc n)1 开始计数。 pr-str 是漂亮的打印字符串。 str 将所有字符串组件连接在一起。

clojure 的核心库中还有一个方便的格式化工具:cl-format,它是 common lisp 格式语法的端口。它包括打印集合的好方法:

(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

关于 format 可以做什么的更多信息是 here