Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure type conversion string to symbol

Tags:

clojure

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

like image 427
vanamonde Avatar asked Mar 09 '10 15:03

vanamonde


1 Answers

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.)

like image 80
Michał Marczyk Avatar answered Oct 21 '22 15:10

Michał Marczyk