我的老师很难解释。他给了我们一个问题,答案是他无法解释,导致我自己不了解太多。
是否有人可以分解这个答案是如何产生的?据我所知,car
返回列表的第一个元素,cdr
返回第一个元素后的所有元素。
提前感谢您的阅读。
假设Lisp变量E的值如下:
(setf e '((-1 -2)
((90 91) 92 93 94 95 96 97 98)
(9 19 29 39 49 59 69 79 89)))
编写一个LISP表达式,该表达式不涉及任何数字,但会对列表求值:
(-2 91 (19 29 39 49 59 69 79 89))
回答:
(list (cadar e) (cadr (caadr e)) (cdaddr e))
在Common Lisp(以及其他Lisp语言)中,像cadar
或cdaddr
等函数(在第一个d
之后和最后一个a
之前,你最多可以有4个字符c
或r
)是car
函数组合的缩写和cdr
有以下规则:每个a
对应一个car
,每个d
对应一个cdr
。
换句话说,(caar x)
相当于(car (car x))
,(caddr x)
相当于(car (cdr (cdr x)))
等等。
例如,在你的例子中,qazxsw poi意味着qazxsw poi,即:
(cadar e)
这里是其他等价物:
(car (cdr (car e)))
所以take the (car e), which is (-1 -2)
take the cdr of the previous value, which is the list (-2)
take the car of this list, that is the integer -2
相当于:
(cadr (caadr e)) = (car (cdr (car (car (cdr e)))))
(cdaddr e) = (cdr (car (cdr (cdr e))))
产生预期结果(您可以通过以正确的顺序应用所有函数来验证这一点)。