Clojure 中的宏和函数
我在这个 Clojure 教程中读到了以下行 - http://java.ociweb.com /mark/clojure/article.html#宏
'由于宏不评估它们的参数,因此可以将不带引号的函数名称传递给它们,并且可以构造对带有参数的函数的调用。函数定义不能做到这一点,而是必须传递包装函数调用的匿名函数。
如果它是正确的,那么为什么这会起作用,因为函数立方体不是匿名的 -
(defn something [fn x]
(fn x))
(defn cube [x]
(* x x x))
(something cube 4)
I read the following line in this Clojure tutorial - http://java.ociweb.com/mark/clojure/article.html#Macros
'Since macros don't evaluate their arguments, unquoted function names can be passed to them and calls to the functions with arguments can be constructed. Function definitions cannot do this and instead must be passed anonymous functions that wrap calls to functions.'
If it is correct, then why does this work since the function cube is not anonymous-
(defn something [fn x]
(fn x))
(defn cube [x]
(* x x x))
(something cube 4)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的,这句话似乎不正确。我认为它想说的是,你不能将看起来像函数调用的东西传递给不带引号的函数:
在这种情况下, (bla 1 2 3) 将被评估为函数调用,并且返回值将传递给某个函数。
对于宏,传递的是 list
(bla 1 2 3)
,然后可以通过插入参数来构造新的函数调用,或者做点别的事。正如您所展示的那样,您绝对仍然可以将一个函数传递给另一个函数,这是一种完全记录和预期使用的技术。
You're right, that quote doesn't seem to be correct. I think what it's trying to say is that you cannot pass something that looks like a function call to a function unquoted:
In this case, (bla 1 2 3) will be evaluated as a function call and the return value will be passed to some-function.
In the case of a macro, what is passed is the list
(bla 1 2 3)
, which can then be used to construct a new function call by inserting arguments, or do something else.You can definitely still pass a function to another function as you showed, and that's a completely documented and expected technique to use.
defn 是 s 宏,代码扩展为,因为您需要匿名函数:
(def some (fn [fn x] (fn x)))
。我想他指的就是这个。defn is s macro, the code is expanded to, since you need the anonymous function:
(def something (fn [fn x] (fn x)))
. I think that what's he is referring to.