Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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.

like image 270
rishi kant Avatar asked Jun 26 '16 06:06

rishi kant


People also ask

How do I print a list of elements separately?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.

How do you print a vector in Clojure?

You can also use clojure. pprint/pprint to pretty-print it. This can be helpful with large, complex data structures. These methods work for all of the basic Clojure data structures.

How do you print on separate lines in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.


2 Answers

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.

like image 107
Sam Estep Avatar answered Oct 11 '22 11:10

Sam Estep


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.

like image 18
Magos Avatar answered Oct 11 '22 09:10

Magos