vanamonde
vanamonde

Reputation: 167

clojure type conversion string to symbol

in clojure i have vector ["myfn1" "myfn2" "myfn3"] how can i call functions named "myfn1" ... using strings from that vector

Upvotes: 12

Views: 5608

Answers (1)

Michał Marczyk
Michał Marczyk

Reputation: 84331

To call a function bound to Var myfn1 given the string "myfn1", you could do something like this:

((resolve (symbol "myfn1")) ...) ; ... indicates where to put any arguments

So, given your example vector and assuming that you don't need to pass any additional arguments to your functions (it's straighforward enough to modify this code if you do), you could do the following:

(map #((resolve (symbol %))) ["myfn1" "myfn2" "myfn3"])

E.g.

user=> (map #((resolve (symbol %1)) %2) ["println" "print" "prn"] ["asdf" "asdf" "asdf"])
(asdf
asdfnil "asdf"
nil nil)

(The nils are the return values from the printing functions; note how there's no linebreak after the asdf produced by print and the asdf produces by prn is quoted.)

Upvotes: 14

Related Questions