使用Lisp宏可以做什么,而使用一等函数则不能做什么? [英] What can you do with Lisp macros that you can't do with first-class functions?

查看:85
本文介绍了使用Lisp宏可以做什么,而使用一等函数则不能做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我了解Lisp宏及其在编译阶段的作用.

I think I understand Lisp macros and their role in the compilation phase.

但是在Python中,您可以将一个函数传递给另一个函数

But in Python, you can pass a function into another function

def f(filename, g):
  try:                                
     fh = open(filename, "rb") 
     g(fh)
  finally:
     close(fh) 

因此,我们在这里得到了懒惰的评估.我可以使用宏而不是使用函数作为一流对象怎么办?

So, we get lazy evaluation here. What can I do with macros and not with functions as first class objects?

推荐答案

首先Lisp也具有一流的功能,因此您也可以问:如果我已经拥有一流的,为什么我需要Lisp中的宏?功能".答案是一流的函数不允许您使用语法.

First of all Lisp has first-class functions too, so you could as well ask: "Why do I need macros in Lisp if I already have first-class functions". The answer to that is that first-class functions don't allow you to play with syntax.

在外观上,一流的函数使您可以编写f(filename, some_function)f(filename, lambda fh: fh.whatever(x)),但不能编写f(filename, fh, fh.whatever(x)).尽管可以说这是一件好事,因为在最后一种情况下,fh的突然来源还不清楚.

On a cosmetic level, first-class functions allow you to write f(filename, some_function) or f(filename, lambda fh: fh.whatever(x)), but not f(filename, fh, fh.whatever(x)). Though arguably that's a good thing because in that last case it is a lot less clear where fh suddenly comes from.

更重要的是,函数只能包含有效的代码.因此,您无法编写将函数作为参数并反向"执行的高阶函数reverse_function,以致reverse_function(lambda: "hello world" print)将执行print "hello world".使用宏,您可以执行此操作.当然,这个特定示例非常愚蠢,但是在嵌入领域特定语言时,此功能非常有用.

More importantly functions can only contain code that is valid. So you can't write a higher-order function reverse_function that takes a function as an argument and executes it "in reverse", so that reverse_function(lambda: "hello world" print) would execute print "hello world". With a macro you can do this. Of course this particular example is quite silly, but this ability is enormously useful when embedding domain specific languages.

例如,您无法在python中实现常见的lisp的loop构造.地狱,如果它不是真正内置的,甚至不能在python中实现python的for ... in构造-至少不是使用该语法.当然,您可以实现for(collection, function)之类的东西,但是要漂亮得多.

For example you couldn't implement common lisp's loop construct in python. Hell, you couldn't even implement python's for ... in construct in python if it wasn't really built-in - at least not with that syntax. Sure you could implement something like for(collection, function), but that's a lot less pretty.

这篇关于使用Lisp宏可以做什么,而使用一等函数则不能做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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