使用#a.k.a.阅读宏 [英] Use of # a.k.a. read-macro
问题描述
阅读道格·霍伊特(Doug Hoyte)的著作《让Lambda越过》,我发现了以下对#.
符号的描述,也就是阅读宏:
Reading book "Let Over Lambda" by Doug Hoyte, I found the following description of #.
sign, a.k.a. read-macro:
#随COMMON LISP内置的基本读取宏是#.读取时间eval宏.通过此读取宏,您可以将对象嵌入无法序列化但可以用少量lisp代码创建的读取形式.
A basic read macro that comes built in with COMMON LISP is the #. read-time eval macro. This read macro lets you embed objects into the forms you read that can't be serialised, but can be created with a bit of lisp code.
从第4章开始,可以在这里找到本书的大部分内容: http://letoverlambda.com/index.cl/toc
It's from Chapter 4, most part of the book can be found here: http://letoverlambda.com/index.cl/toc
这是本书中的示例,该示例显示了每次相同的表达式可能如何被不同地读取:
This is example from the book that shows how the same expression may be read differently every time:
* '(football-game
(game-started-at
#.(get-internal-real-time))
(coin-flip
#.(if (zerop (random 2)) 'heads 'tails)))
(FOOTBALL-GAME
(GAME-STARTED-AT 187)
(COIN-FLIP HEADS))
* '(football-game
(game-started-at
#.(get-internal-real-time))
(coin-flip
#.(if (zerop (random 2)) 'heads 'tails)))
(FOOTBALL-GAME
(GAME-STARTED-AT 309)
(COIN-FLIP TAILS))
接下来,作者演示了一些铁杆花样,并使用#
宏创建了变体.
Next, author demonstrates some hardcore tricks, creating variations with #
macro.
因此,事实证明#'
也是某种读取宏,它通常在表示函数名称的符号之前使用.但是有必要,他在那里的工作到底是什么?
So, it turns out that #'
is also some kind of reading macro, and it's usually used before symbols that represent names of functions. But is it necessary, and what's exactly his job there?
我可以使用#'
或不使用#'
来放置高阶函数的符号:
I can put symbol for higher-order functions with #'
or without it:
CL-USER> (defun test nil t)
TEST
CL-USER> (funcall #'test)
T
CL-USER> (funcall 'test)
T
取得同样的成功.
推荐答案
您可以通过两种方式调用函数的全局定义:
You can call global definitions of functions both ways:
CL-USER> (defun test nil t)
TEST
CL-USER> (funcall #'test)
T
CL-USER> (funcall 'test)
T
但是看到这个:
CL-USER 10 > (defun foo () 42)
FOO
CL-USER 11 > (flet ((foo () 82))
(print (foo))
(print (funcall 'foo))
(print (funcall #'foo)))
82 ; the local definition
42 ; the symbol references the global definition
82 ; (function foo) / #'foo references the local definition
(funcall 'foo)
从符号中查找功能.
(funcall #'foo)
从词法环境中调用该函数.如果没有,则使用全局定义.
(funcall #'foo)
calls the function from the lexical environment. If there is none the global definition is used.
#'foo
是(function foo)
的简写形式.
CL-USER 19 > '#'foo
(FUNCTION FOO)
这篇关于使用#a.k.a.阅读宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!