[英]Compact way in Clojure to print a variable number of command line arguments?
我是 Clojure 的新手。 我想我正在尝试通过程序解决这个问题,并且在 Clojure 中必须有更好(更实用)的方法来做到这一点......
-main function 可以接收可变数量的“args”。 我想将它们打印出来,但要避免 IndexOutOfBoundsException。 我以为我可以模仿 Java 并使用案例失败来最小化所涉及的代码,但这不起作用:
(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
但在开头添加索引号。 因此,它逐项通过 arguments,将索引和项打包到一个vector
中,并通过解构索引号和项映射到[n arg]
。
由于 clojure 从0
开始计数,因此您使用(inc n)
从1
开始计数。 pr-str
是漂亮的打印字符串。 str
将所有字符串组件连接在一起。
clojure 的核心库中还有一个方便的格式化工具: cl-format ,它是通用 lisp 格式语法的端口。 它包括一个打印出 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
有关format
可以做什么的更多信息在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.