I use lein new app test-println to create a clojure app and launch the repl with lein repl, then I enter (map println [1 2 3 4 5 6]) and get the expected result:
test-println.core=> (map println [1 2 3 4 5 6])
1
2
3
4
5
6
(nil nil nil nil nil nil)
However if I add (map println [1 2 3 4 5 6]) to the end of src/test_println/core.clj:
(ns test-println.core
(:gen-class))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!")
(map println [1 2 3 4 5 6]))
lean run prints only Hello, World!.
map is lazy. To quote the first sentence of the documentation (emphasis added):
Returns a lazy sequence consisting of the result of applying f to the
set of first items of each coll, followed by applying f to the set of
second items in each coll, until any one of the colls is exhausted.
The REPL forces evaluation of the expression to show the result, but nothing in your code does. dorun would solve this, but you probably should look at doseq / doall instead.
If your goal is to run a single procedure over every item in a single collection, you should use run!:
(run! println [1 2 3 4 5 6])
;; 1
;; 2
;; 3
;; 4
;; 5
;; 6
;;=> nil
In cases where the action you need to perform on each collection is more complex than simply applying an existing function, doseq may be more convenient, but run! is a better choice here.
Related
If I try this, I get back results I expect: a list of trues and falses for each entry in the vector.
(deftest test-weird
(let [x {:nums [1 2 3 4 5 6 7 8]}
res (update x :nums #(map even? %))]
(println res)))
results: {:nums (false true false true false true false true)}
If I try this with drop-while, I get back the vector unchanged, where as I was expecting to get back a list of just the odd entries.
(deftest test-weird
(let [x {:nums [1 2 3 4 5 6 7 8]}
res (update x :nums #(drop-while even? %))]
(println res)))
results: {:nums (1 2 3 4 5 6 7 8)}
What am I doing wrong?
The first item is 1, which is not even. Thus, no items are dropped from the sequence.
What you really want is #(remove even? %). However, I think it reads better to say #(filterv odd? %) (i.e. say what you want; don't say what you don't want).
Notice also that there is an eager (vector) version filterv that I always prefer (no such option for remove).
Please see this list of documentation. Especially study the Clojure CheatSheet every day!
While the names filter and remove are very traditional, I always have to think twice to remember if a true predicate is dropped or kept. The definition is:
- filter => "keep-if true ..."
- remove => "drop-if true ..."
In my own code, I usually prefer to use a simple alias to emphasize what is occurring (always eager, as well).
Instead of #(drop-while even? %) which removes all elements in collection until first true event and returns all rest:
either: #(filterv (comp not even?) %)
or: #(remove even? %)
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.
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.
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
I'm wondering why the following have different output orders in an nREPL
(map println [1 2 3])
Result:
1
2
3
(nil nil nil)
Versus
(map print [1 2 3])
Result:
(nil nil nil)123
Why does applying print show the return value and then display 123?
Also to note, that this works in REPL, in the code you need to use (dorun), as map produces a lazy sequence, and dorun actually forces print to happen:
(dorun (map print [1 2 3])) ;=> 123
Actually, you may see a different order if you run the second one multiple times. print does not print any newlines, so the output buffer is not flushed. You could very well also see:
Result:
123(nil nil nil)
I suppose the first example could possibly change order, too, but the REPL has *flush-on-newline* set to true by default.
It looks pretty much like result of output stream buffering.
You could forcibly print all data in output stream buffer by calling flush function:
(defn print! [& args]
(apply print args)
(flush))
(map print! [1 2 3])
; => 123(nil nil nil)
For example
(map #(+ 10 %1) [ 1 3 5 7 ])
Will add 10 to everything
Suppose I want to map everything to the constant 1. I have tried
(map #(1) [ 1 3 5 7 ])
But I don't understand the compiler error.
(map #(1) [ 1 3 5 7 ])
Won't work for two reasons:
#(1) is a zero-argument anonymous function, so it won't work with map (which requires a one-argument function when used with one input sequence).
Even if it had the right arity, it wouldn't work because it is trying to call the constant 1 as a function like (1) - try (#(1)) for example if you want to see this error.
Here are some alternatives that will work:
; use an anonymous function with one (ignored) argument
(map (fn [_] 1) [1 3 5 7])
; a hack with do that ignores the % argument
(map #(do % 1) [1 3 5 7])
; use a for list comprehension instead
(for [x [1 3 5 7]] 1)
; use constantly from clojure.core
(map (constantly 1) [1 3 5 7])
Of the above, I think the versions using constantly or for should be preferred - these are clearer and more idiomatic.
The anonymous function #(+ 10 %1) is equivalent to:
(fn [%1]
(+ 10 %1))
Whereas #(1) is equivalent to:
(fn []
(1))
And trying to call 1 as a function with no args just won't work.
I got this from clojure.org
by googling the words "clojure constant function" as I am just beginning to look at clojure
(map (constantly 9) [1 2 3])
cheers
What's the difference between doseq and for in Clojure? What are some examples of when you would choose to use one over the other?
The difference is that for builds a lazy sequence and returns it while doseq is for executing side-effects and returns nil.
user=> (for [x [1 2 3]] (+ x 5))
(6 7 8)
user=> (doseq [x [1 2 3]] (+ x 5))
nil
user=> (doseq [x [1 2 3]] (println x))
1
2
3
nil
If you want to build a new sequence based on other sequences, use for. If you want to do side-effects (printing, writing to a database, launching a nuclear warhead, etc) based on elements from some sequences, use doseq.
Note also that doseq is eager while for is lazy. The example missing in Rayne's answer is
(for [x [1 2 3]] (println x))
At the REPL, this will generally do what you want, but that's basically a coincidence: the REPL forces the lazy sequence produced by for, causing the printlns to happen. In a non-interactive environment, nothing will ever be printed. You can see this in action by comparing the results of
user> (def lazy (for [x [1 2 3]] (println 'lazy x)))
#'user/lazy
user> (def eager (doseq [x [1 2 3]] (println 'eager x)))
eager 1
eager 2
eager 3
#'user/eager
Because the def form returns the new var created, and not the value which is bound to it, there's nothing for the REPL to print, and lazy will refer to an unrealized lazy-seq: none of its elements have been computed at all. eager will refer to nil, and all of its printing will have been done.