4

I'm a Clojure newbie. I'm trying to understand why the second form doesn't work:

First form:

user=>(def nums(range 3))
(0 1 2)
user=>(map #(list %1) nums)
((0) (1) (2))

Second form:

user=> (map #(list %1) (0 1 2))
java.lang.ClassCastException: java.lang.Integer cannot be cast to clojure.lang.IFn 
(NO_SOURCE_FILE:0)

4 Answers 4

11

The problem is the expression (0 1 2), which is interpreted as 0 applied to 1 and 2; that's impossible because 0 isn't a function.

(map #(list %1) '(0 1 2))

works as intended, though.

5

Because (0 1 2) means call function 0 with args 1 and 2, but 0 is not a function. So you need to make is a list rather than function application using quote or list function i.e '(0 1 2) OR (list 0 1 2)

3
  • Yes, I've realized after submitting the question, but couldn answer myself because of StackOverflow restrictions. Thank you. Dec 7, 2011 at 16:26
  • Actually, you can answer your own questions on Stackoverflow.
    – Cubic
    Oct 7, 2012 at 16:11
  • 1
    Maybe his rank was too low or something?
    – sjas
    Dec 26, 2013 at 22:44
4

larsmans and Ankur have it. I realize this is a trivial example, but it would probably be more idiomatic to use a vector rather than a list:

(map #(list %1) [0 1 2])

You can also use % instead of %1 when there's only one arg passed to the anonymous function.

(map #(list %) [0 1 2])
1
user=> (map list (range 3))
((0) (1) (2))
user=> (map list '(0 1 2))
((0) (1) (2))
user=> (map list [0 1 2])
((0) (1) (2))

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.