字符串名称中的clojure解析函数 [英] clojure resolving function from string name

查看:41
本文介绍了字符串名称中的clojure解析函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在clojure 1.2RC1中,我希望基于其名称作为字符串来获取一个函数并对其进行评估.

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

函数定义

(ns my-ns)

(defn mycar [x] (first x))

以下工作有效:

((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?

推荐答案

这对我有效,无需使用eval:

This worked for me without using eval:

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

之所以可行,是因为resolves在当前名称空间中找到了mycar var,并且var调用了它所绑定的函数.这是第一个示例的简短版本.我只是为了避免使用eval而使用它.

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.

这篇关于字符串名称中的clojure解析函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆