Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nothing happen inside my Clojure loop

I have a small code that doesn't want to work at all when I perform a loop like the following:

...

    (defn my-function []
        (println "Hi")   ;this works
        (for [i (range 10)] (println "Hello")  ;this doesn't work!
          )
    )

...

I can't understand what the problem is, all the code inside the loop seem to be ignored, while the "Hi" print without problems

I call 'myfunction' through a GUI button event, like this:

...
    (.append output-text (with-out-str  (time (my-function))))
...

Do you think the problem could reside in the GUI or something else I am missing? Any suggestion? I know I should use the REPL to test it but it doesn't work with Netbeans... :S

Thanks very much for your help.

like image 976
nuvio Avatar asked Apr 02 '12 20:04

nuvio


2 Answers

The for macro is lazy, so it will not invoke your function unless the return value is actually needed.

Use the doseq function instead. It will force the evaluation of your code, and thus is not lazy. It has the same "syntax" as for and allows you to account for side effecting functions such as println.

like image 94
Jeremy Avatar answered Nov 18 '22 07:11

Jeremy


Another way of making this is using "dorun", if I remember corretly dorun is pretended for when you make side effects (like println). The function should look like this:

(defn my-function[]
  (println "Hi")
  (dorun (for [i (range 10)] (println "Hello"))))
like image 33
nMoncho Avatar answered Nov 18 '22 05:11

nMoncho