15

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.

3 Answers 3

23

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.

0
18

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.

0
2

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
3
  • The main difference is when the sequence you're printing is lazy; compare (run! println (range)) and (println (unlines (range))).
    – Sam Estep
    Jun 28, 2016 at 19:45
  • @SamEstep you're right, it's not quite as useful on an infinite list. Lazy sequences will have to be realized before building the String. But in general, confining side-effecting code to the boundaries is not a bad strategy. A function that returns a String is much more testable than one that prints to the console. Jun 28, 2016 at 23:16
  • 1
    Agreed. It's just a question of what task specifically needs to be done. In this particular case of printing five already known items separated by newlines, I would say that your unlines solution is better. But in the more general case of performing actions (which may involve input or output or both) repeatedly, precalculating the result isn't always an option.
    – Sam Estep
    Jun 29, 2016 at 0:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.