in clojure i have vector ["myfn1" "myfn2" "myfn3"] how can i call functions named "myfn1" ... using strings from that vector
+3
A:
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 nil
s 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.)
Michał Marczyk
2010-03-09 16:32:09