Clojure 中的宏和函数

发布于 2024-11-02 10:35:44 字数 438 浏览 1 评论 0原文

我在这个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

圈圈圆圆圈圈 2024-11-09 10:35:44

你是对的,这句话似乎不正确。我认为它想说的是,你不能将看起来像函数调用的东西传递给不带引号的函数:

(some-function (bla 1 2 3))

在这种情况下, (bla 1 2 3) 将被评估为函数调用,并且返回值将传递给某个函数。

(some-macro (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:

(some-function (bla 1 2 3))

In this case, (bla 1 2 3) will be evaluated as a function call and the return value will be passed to some-function.

(some-macro (bla 1 2 3))

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.

不知在何时 2024-11-09 10:35:44

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文