问题
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