宏和函数在Clojure [英] Macros and functions in Clojure

查看:187
本文介绍了宏和函数在Clojure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了这篇Clojure教程中的以下一行: http:// java。 ociweb.com/mark/clojure/article.html#Macros


'由于宏未评估其参数,因此未引用函数名可以传递给它们,并且可以构造对带有参数的函数的调用。函数定义不能这样做,而是必须传递匿名函数来封装对函数的调用。'


如果它是正确的,这个工作自从函数多维数据集不是匿名的 -

 (defn something [fn x] 
(fn x))

(defn cube [x]
(* xxx))

(something cube 4)


解决方案

你说得对,报价似乎不正确。我想要说的是,你不能将看起来像函数调用的函数传递给未引用的函数:

 (some-function(bla 1 2 3))

bla 1 2 3)将作为函数调用进行计算,并且返回值将被传递给某个函数。

  -macro(bla 1 2 3))

在宏的情况下,传递的是 $ ,然后可以通过插入参数来构造一个新的函数调用, p>

你可以把一个函数传递给另一个函数,这是一个完全记录和预期的技术。


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)

解决方案

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.

这篇关于宏和函数在Clojure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆