开发者

Macros and functions in Clojure

开发者 https://www.devze.com 2023-02-27 00:45 出处:网络
I read the following line in this Clojure tutorial - http://java.ociweb.com/mark/clojure/article.html#Macros

I read the following line in this Clojure tutorial - http://java.ociweb.com/mark/clojure/article.html#Macros

'Since m开发者_开发问答acros 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)


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消