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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With