Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this anonymous function starting with println result in a NullPointerException?

Tags:

clojure

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.

like image 267
noahlz Avatar asked Sep 21 '12 16:09

noahlz


2 Answers

The anonymous fn literal #() does not have an implicit do.

like image 110
dnolen Avatar answered Nov 15 '22 11:11

dnolen


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.

like image 20
M Smith Avatar answered Nov 15 '22 11:11

M Smith