使用 Clojure 进行函数式编程
大师
这里有一个问题要问你:我正在开发一个 clojure 程序, 涉及将函数传递给函数。
我有这样的事情:
(defn funct-op [args]
((first args)
(second args)
(last args) )
(funct-op '(+ 2 2))
我怎样才能哄骗funct-op给我4而不是我的2 目前得到?我可能需要将函数传递给宏作为我的 项目取得进展。关于如何做到这一点有什么建议吗?感谢您的帮助!
gurus
Here's a question for you: I am working on a clojure program that
involves passing functions to functions.
I have something like:
(defn funct-op [args]
((first args)
(second args)
(last args) )
(funct-op '(+ 2 2))
How can I coax funct-op into giving me 4 rather than the 2 I am
currently getting? I may need to pass a function to a macro as my
project progresses. Any tips on how to do that? Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了将“+”转换为函数,您可以使用resolve。这应该适用于核心函数,但您可能需要 ns-resolve 来实现自定义函数。然后,您可以使用 apply 将其余参数传递给该函数。
(defn funct-add [args] (apply (resolve (first args)) (rest args)))
不确定您的最终目标是什么,但我认为这就是您正在寻找的答案。
In order to turn the '+' into a function you can use resolve. This should work on core functions, but you may need ns-resolve for custom functions. You can then use apply to pass the rest of the arguments to that function.
(defn funct-add [args] (apply (resolve (first args)) (rest args)))
Not sure what your end goal really is but I think that is the answer you were looking for.
funct-add 到底应该做什么?如果是
(funct-add '(- 2 2))
怎么办?无论如何,请考虑申请,即使已经结束:
比较这些形式可能会有所启发:
注意最后一个形式是如何评估的;它不仅仅是一个“文字列表”——不再有符号了! :-)
快乐编码。
What is
funct-add
really supposed to do? What if it was(funct-add '(- 2 2))
?Anyway, consider apply, even wrapped up:
Comparing these forms may be enlightening:
Note how the last one was evaluated; it is not just a "literal list" -- no symbol there anymore! :-)
Happy coding.
我不确定,这些东西?
I'm not sure, these things?