计算机程序的结构和解释有以下footnote :
Another way to define the selectors and constructor is
(define make-rat cons)
(define numer car)
(define denom cdr)
The first definition associates the name
make-rat
with the value of the expressioncons
, which is the primitive procedure that constructs pairs. Thusmake-rat
andcons
are names for the same primitive constructor.Defining selectors and constructors in this way is efficient: Instead of
make-rat
callingcons
,make-rat
iscons
, so there is only one procedure called, not two, whenmake-rat
is called. On the other hand, doing this defeats debugging aids that trace procedure calls or put breakpoints on procedure calls: You may want to watchmake-rat
being called, but you certainly don't want to watch every call tocons
.
这个建议是否仍然适用?例如,现代调试辅助工具是否仍然以这种方式被击败?
最佳答案
在 Common Lisp 中也可以做到这一点。我们可以设置符号的符号函数。
(setf (symbol-function 'numer)
(function car))
另一种方法是定义这些函数:(defun numer (rat)
(car rat))
现在将有调用这些额外函数的开销。这可以在开发和调试期间提供帮助。在 Common Lisp 中,可以给编译器一个提示,它可以内联函数:
(declaim (inline numer))
然后在用于生产或交付的优化编译代码中,可以内联函数:函数调用开销将不存在,但调用将不再可见。
关于debugging - 将构造函数和选择器定义为 cons、car 和 cdr 是否仍然不可取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65832849/