How to print each item of list in separate line clojure?

丶灬走出姿态 提交于 2020-01-02 01:10:22

问题


I'm very new in clojure. I want to print each item of list in newline. I'm trying like this:

user=> (def my-list '(1 2 3 4 5 ))
;; #'user/my-list
user=> my-list
;; (1 2 3 4 5)
user=> (apply println my-list)
;; 1 2 3 4 5
;; nil

But I want my output must be:

1
2
3
4
5
nil

can anyone tell me, How can I do this? Thanks.


回答1:


This kind of use case (perform a side effect once for each member of a sequence) is the purpose of doseq. Using it here would be like

(doseq [item my-list]
   (println item))

Note that this will not print nil but will return it. Working with it in the REPL will see the return values of all expressions printed, but doesn't happen in e.g. starting your project as a terminal program.




回答2:


If you already have a function that you would like to apply to every item in a single sequence, you can use run! instead of doseq for greater concision:

(run! println [1 2 3 4 5])
;; 1
;; 2
;; 3
;; 4
;; 5
;;=> nil

doseq is useful when the action you want to perform is more complicated than just applying a single function to items in a single sequence, but here run! works just fine.




回答3:


Another strategy would be to build a string from the list that you want to print and then just print the string.

user> (defn unlines [coll]
        (clojure.string/join \newline coll))
#'user/unlines

user> (unlines [1 2 3 4 5])
"1\n2\n3\n4\n5"

user> (println (unlines [1 2 3 4 5]))
1
2
3
4
5
nil


来源:https://stackoverflow.com/questions/38035839/how-to-print-each-item-of-list-in-separate-line-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!