Pranav
Pranav

Reputation: 3312

Macros and functions in Clojure

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)

Upvotes: 4

Views: 843

Answers (2)

0x434D53
0x434D53

Reputation: 1465

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.

Upvotes: -1

Joost Diepenmaat
Joost Diepenmaat

Reputation: 17773

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.

Upvotes: 4

Related Questions