Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

Why is trim() not working inside map in Clojure?

user=> (.trim "   kkk   ")
"kkk"
user=> (map .trim ["jjj " "  llll" " o "] )

CompilerException java.lang.RuntimeException: Unable to resolve symbol: .trim in this context, compiling:(NO_SOURCE_PATH:1:1) 

Any explanation for this behavior ?

I ended up using clojure.string/trim. but wanted to know, whats the prob here ?

Upvotes: 3

Views: 410

Answers (3)

Kyle
Kyle

Reputation: 22268

You need to wrap .trim in an anonymous function so map gets a first-class function instead of a member function:

(map #(.trim %) ["jjj " "  llll" " o "])

Alternatively, you could use memfn to create this first-class function for you:

(map (memfn trim) ["jjj " "  llll" " o "])

Upvotes: 4

Idan Arye
Idan Arye

Reputation: 12623

This works:

(map #(.trim %) ["jjj " "  llll" " o "] )

So I guess .trim is some sort syntactic sugar that doesn't have a meaning outside forms?

Upvotes: 4

BillRobertson42
BillRobertson42

Reputation: 12883

You can't use a member function like that. It's not a Clojure function. Easiest way is to use a closure.

(map #(.trim %) ["  aa " "  bb "])

You can also convert a member function to a Clojure function with memfn.

Upvotes: 1

Related Questions