0

I can return a map from function with following syntax

(defn retmap [bar] { :foo bar })

How do I achieve the same with reader macro syntax? I tried following

(def retmap #({:foo %}))

But calling this function (retmap) gives the error

clojure.lang.ArityException: Wrong number of args (0) passed to: PersistentArrayMap
1

2 Answers 2

2

You can use hash-map:

(def retmap #(hash-map :foo %))

You can see why your example throws an exception by expanding the macro:

(macroexpand `#({:foo %}))
=> (fn* [x] ({:foo x}))

so the constructed map is immediately invoked as a function with no arguments. Maps are functions from keys to values so require an argument to be provided.

Sign up to request clarification or add additional context in comments.

1 Comment

You could explain why the literal doesn't work to gain the check mark :)
1

Another answer which is sometimes quite handy is to use identity:

(def retmap #(identity {:foo %}))

The identity function is used when you are forced to use a function, but you don't want it to do anything

(identity {:foo 42})  => {:foo 42}

(def retmap #(identity {:foo %}))
(retmap 42)  ;=>  {:foo 42}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.