0

I´m trying to map an anonymous function to a collection and I get a ClassCastException.

(defn mapanfn
  [names]
  (map (#(str "Hello %"))
       names))

(mapanfn ["Bobby" "Nico" "Ringo"])

Thanks, R.

2 Answers 2

5

Just take out the extra set of parentheses around your anonymous function, and use format if you want to use a format specifier:

(defn mapanfn
  [names]
  (map #(format "Hello %s" %) names))

Or use str without a format specifier:

(defn mapanfn
  [names]
  (map #(str "Hello " %) names))

In both cases % is referring to the value your anonymous functions is called with, but it will not work inside a string.

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

Comments

1

You made a couple of mistakes here.

The first one, the % symbol should not be a part of a string. Perhaps you confused it with the standard format function. So the expression should be either (str "Hello " %) or (format "Hello %s" %).

The second one, you call your anonymous function twice because of extra parens. The #(str "Hello %") expression returns a function, but putting it into parens calls it once again and gives a string "Hello %". So inside a map function, you are trying to call a string as a function, which is calling an Exception.

The right function in your example would be just #(str "Hello " %).

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.