【发布时间】:2021-02-23 22:45:30
【问题描述】:
我知道通过使用cons 我们可以得到类似的东西:
> (cons 'b 'c)
(B . C)
发生这种情况是因为单元格被分成两部分,其值为B 和C。
我的问题是,你能用list得到同样的结果吗?
【问题讨论】:
标签: lisp common-lisp
我知道通过使用cons 我们可以得到类似的东西:
> (cons 'b 'c)
(B . C)
发生这种情况是因为单元格被分成两部分,其值为B 和C。
我的问题是,你能用list得到同样的结果吗?
【问题讨论】:
标签: lisp common-lisp
你不能让list返回一个点列表,因为"the last argument to list becomes the car of the last cons constructed"在返回的列表中。
但是,您可以让list* 返回一个虚线列表。使用list* 函数,最后一个参数变成了最后一个cons 的cdr,所以:
CL-USER> (list* 'a '(b))
(A B)
CL-USER> (list* 'a 'b '())
(A B)
CL-USER> (list* 'a 'b)
(A . B)
CL-USER> (list* 'a '(b c))
(A B C)
CL-USER> (list* 'a 'b '(c))
(A B C)
CL-USER> (list* 'a 'b 'c '())
(A B C)
CL-USER> (list* 'a 'b 'c)
(A B . C)
例如,(list* 'a 'b 'c '()) 和 (list 'a 'b 'c) 都等价于:
CL-USER> (cons 'a (cons 'b (cons 'c '())))
(A B C)
但(list* 'a 'b 'c) 等价于:
CL-USER> (cons 'a (cons 'b 'c))
(A B . C)
而且,(list* 'a 'b) 等价于:
CL-USER> (cons 'a 'b)
(A . B)
【讨论】:
不,你不能,因为列表是最后一个cdr 为 nil 的 cons 单元的列表。 Lisp 打印机知道约定,在这种情况下不会打印点。
;; a cons cell
CL-USER> (cons 'b 'c)
(B . C)
[o|o]--- c
|
b
;; two cons cells, ending with a symbol: a dot.
CL-USER> (cons 'b (cons 'c 'd))
(B C . D)
;; several cons cells, ending with a symbol: still a dot (at the last cons cell):
CL-USER> (cons 'b (cons 'c (cons 'd (cons 'e 'f))))
(B C D E . F)
;; two cons cells, ending with nil: no dot.
CL-USER> (cons 'b (cons 'c nil))
(B C) ;; and not (B C . NIL)
[o|o]---[o|/]
| |
b c
;; with the list constructor:
CL-USER> (list 'b 'c)
(B C)
【讨论】: