clojure resolving function from string name

*爱你&永不变心* 提交于 2021-02-07 05:22:06

问题


In clojure 1.2RC1, I wish to obtain a function based on its name as string and evaluate it.

Function definition

(ns my-ns)

(defn mycar [x] (first x))

The following worked:

((ns-resolve *ns* (symbol "mycar")) '(3 4))
((intern *ns* (symbol "mycar")) '(3 4))
((eval (symbol "mycar")) '(3  4))

but they seem ugly. Is there a better way? If not, which of the above is the most idiomatic?


回答1:


This worked for me without using eval:

user> (defn mycar [x] (first x))
#'user/mycar
user> ((resolve (symbol "mycar")) [1 2 3])
1

This works because resolves finds the mycar var in the current namespace and the var calls the function it's bound to. This is a shorter version of your first example. I'd use it just so that I could avoid using eval.



来源:https://stackoverflow.com/questions/3407921/clojure-resolving-function-from-string-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!