Search code examples
clojure

Anonymous functions: different syntax strange behavior


Why we get nil using fn and NullPointerException using # ??

Clojure 1.8.0
Java HotSpot(TM) 64-Bit Server VM 1.8.0_91-b14

> ((fn [x] (println x) (println x)) "I have a question")
I have a question
I have a question
=> nil

> (#((println %) (println %)) "I have a question")
I have a question
I have a question
NullPointerException   user/eval1155/fn--1156 (form-init5537026255318038171.clj:1)

Solution

  • In your first example: the last statement is the return value of the function. The return value of println is nil. Therefor you see the two prints and then from your REPL the return of nil. See below for a marker, where it happens (imaging an implicit return seen in imperative languages):

    > ((fn [x] (println x) (println x)) "I have a question")
                           ^~~~~~~~~~~
    

    Your second example: The body of an anonymous function is directly called. You should add a do inside the anon fn. Otherwise (as in your example), This will use the result of the first print as a function to call; add do at marker:

    > (#((println %) (println %)) "I have a question")
         ^
    

    You can see this unfold, if you check the resulting code after the reader does its magic (see marker again):

    user=> '(#((println %) (println %)) "I have a question")
    ((fn* [p1__8265#] ((println p1__8265#) (println p1__8265#))) "I have a question")
                       ^