奇怪的Lisp报价方案

奇怪的Lisp报价方案

本文介绍了奇怪的Lisp报价方案-Graham的《 Lisp报价》,第37页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Graham的著作《 On Lisp》,无法理解第37页上的以下示例:

I'm working my way through Graham's book "On Lisp" and can't understand the following example at page 37:


If we define exclaim so that its return value
incorporates a quoted list,

(defun exclaim (expression)
  (append expression ’(oh my)))

>  (exclaim ’(lions and tigers and bears))
(LIONS AND TIGERS AND BEARS OH MY)
> (nconc * ’(goodness))
(LIONS AND TIGERS AND BEARS OH MY GOODNESS)

could alter the list within the function:

> (exclaim ’(fixnums and bignums and floats))
(FIXNUMS AND BIGNUMS AND FLOATS OH MY GOODNESS)

To make exclaim proof against such problems, it should be written:
(defun exclaim (expression)
  (append expression (list ’oh ’my)))

有人知道这里发生了什么吗?这严重影响了我对报价功能的思维模式.

Does anyone understand what's going on here? This is seriously screwing with my mental model of what quoting does.

推荐答案

nconc是一种破坏性操作,通过更改其尾部来更改其第一个参数.在这种情况下,这意味着常量列表'(oh my)会出现新的尾巴.

nconc is a destructive operation that alters its first argument by changing its tail. In this case, it means that the constant list '(oh my) gets a new tail.

希望更清楚地说明这一点.有点像这样:

To hopefully make this clearer. It's a bit like this:

; Hidden variable inside exclaim
oh_my = oh → my → nil

(exclaim '(lions and tigers and bears)) =
    lions → and → tigers → and → bears → oh_my

(nconc * '(goodness)) destructively appends goodness to the last result:
    lions → and → tigers → and → bears → oh → my → goodness → nil
so now, oh_my = oh → my → goodness → nil

(list 'oh 'my)替换'(oh my)可以解决此问题,因为不再有一个常量被所有人和其他人共享.每次调用exclaim都会生成一个新列表(list函数的作用是创建全新的列表).

Replacing '(oh my) with (list 'oh 'my) fixes this because there is no longer a constant being shared by all and sundry. Each call to exclaim generates a new list (the list function's purpose in life is to create brand new lists).

这篇关于奇怪的Lisp报价方案-Graham的《 Lisp报价》,第37页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:29