【问题标题】:Compact way in Clojure to print a variable number of command line arguments?Clojure 中打印可变数量的命令行参数的紧凑方式?
【发布时间】:2020-08-09 05:22:01
【问题描述】:

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

【问题讨论】:

    标签: clojure switch-statement case indexoutofboundsexception


    【解决方案1】:
    (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 将所有字符串组件连接在一起。

    【讨论】:

      【解决方案2】:

      clojure 的核心库中还有一个方便的格式化工具:cl-format,它是通用 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

      【讨论】:

      • cl-format 库能否处理带有可变数量参数而不是集合向量的可变参数函数?
      • 当然,没有区别
      猜你喜欢
      • 2019-05-26
      • 1970-01-01
      • 2013-01-29
      • 2013-10-10
      • 2017-03-24
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      相关资源
      最近更新 更多