Is this an expected behaviour, or it's a problem with my Clojure installations (I'm checking it on Windows and Linux)?
I have a simple project, created with lein new app testfor. Here's the code of src/testfor/core.clj:
(ns testfor.core
(:gen-class))
(defn -main [& args]
(println "hello")
(for [x [1 2 3]]
(println x)))
When I run lein repl and invoke (-main) from the REPL, the output is this:
testfor.core=> (-main)
hello
1
2
3
But then I run the application with lein run, or lein uberjar and run the generated JAR file, the output is this:
$ lein run
hello
So, it somehow doesn't run the for loop.
Am I doing something wrong here?
I believe this is because for returns a lazy-sequence of elements - https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/for
In the example when you call the -main function from the repl, in this case the last expression in the function is returned from the function call (just like any other function call). The REPL sees the lazy-seq and attempts to print it, which requires realising the seq, which will evaluate the println statements.
In the example when you Leiningen calls the main method, it is like calling a main method on a Java class which has a void return type public static void main. Clojure will see it as lazy and nothing tries to realise the seq so the println expressions are never evaluated.
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