Search code examples
clojure

I don't understand the ArityException when I use a function literal


I'm struggling to understand why...

(map (fn [x] {:hello x}) ["moe" "larry" "curly"])
=> ({:hello "moe"} {:hello "larry"} {:hello "curly"})

...works like a champ but...

(map #({:hello %}) ["moe" "larry" "curly"])
ArityException Wrong number of args (0)...

...throws ArityException Wrong number of args (0) passed to: PersistentArrayMap clojure.lang.AFn.throwArity (AFn.java:429)

What am I doing wrong in my function literal?


Solution

  • You can see the issue if you expand you use of the # macro:

    (macroexpand `#({:hello %}))
    
    => (fn* [p1__1__2__auto__] ({:hello p1__1__2__auto__}))
    

    this returns a function of a single argument which when applied calls the constructed hash map with no arguments, hence the ArityException you see when evaluating the sequence returned from map. You could use hash-map instead of a map literal:

    (map #(hash-map :hello %) ["moe" "larry" "curly"])