I am learning about pmap and wrote the following function:
(pmap #((println "hello from " (-> (Thread/currentThread) .getName))
(+ %1 %2))
[1 1 1] [-1 -1 -1])
When run, the result is a NullPointerException
(hello from clojure-agent-send-off-pool-4
hello from clojure-agent-send-off-pool-3
hello from clojure-agent-send-off-pool-5
NullPointerException user/eval55/fn--56 (NO_SOURCE_FILE:11)
Why is this happening? I have understood and observed the body of a fn to be an implicit do.
The anonymous fn literal #() does not have an implicit do.
You have println in 2 parens so the result of println is evaluated. println always returns nil hence the NullPointerException.
Try removing the extra parens from the #():
(pmap #(println "hello from "
(-> (Thread/currentThread) .getName)
(+ %1 %2))
[1 1 1] [-1 -1 -1] )
EDIT:
Then you will need the do as mentioned in other comments like:
(pmap #(do (println "hello from "
(-> (Thread/currentThread) .getName))
(+ %1 %2))
[1 1 1] [-1 -1 -1] )
The reason the do is necessary in the #() reader macro is not that functions don't include an implicit do but has to do with the way the macro expands. Basically, that macro assumes a single form hence the need for the explicit do.
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