As we know, (map f [a b c]) is equivalent to [(f a) (f b) (f c)].
My question is: The evaluation result of (map #(- (int %) (int 0円)) "1234") is (1 2 3 4), why does it return the results of applying #(- (int %) (int 0円)) to every digits of "1234", rather than the string "1234" as a whole? How should I understand this code example?
2 Answers 2
map calls seq on all arguments after the first. seq turns a string into a sequence of characters.
Comments
Clojure can treat a string as a sequence - of characters. This is useful because you can:
- map things over the string
- partition the string
- get locations by index
- do everything else sequences do.
It's perhaps a bit annoying having to remember to put the resulting sequence back into a string by wrapping the sequence manipulating expression in a call to str.
2 Comments
map which calls seq on args, and showing (apply str (map f string)) as the canonical way to get a string back out the other side.map's behavior.
(map f [a b c])isn't exactly the same as the result of[(f a) (f b) (f c)], sincemapreturns a lazy sequence rather than a vector. I think it's correct to say that the result of(map f [a b c])is the same as the result of(lazy-seq [(f a) (f b) (f c)]), and that result of(vec (map f [a b c]))is the same as the result of[(f a) (f b) (f c)]. (If I'm wrong about some details, more knowledgeable people will hopefully correct me.)mapif you just want to call a function using a single argument. If that's what you want, then don't usemap:(#(- (int %) (int 0円)) "1234")ClassCastException java.lang.String cannot be cast to java.lang.Character ...- surely not what's intended.Integer/parseIntto convert the string to an int instead of theint"cast" that works for chars. The point is that I don't really understand the OP's question—*if you just want to apply the function to the string (not the individual characters), why don't you just call it directly rather than usingmap?* Apparently I'm missing something...