【发布时间】:2013-05-16 03:19:41
【问题描述】:
我想知道为什么
'((atom1) . atom2)
是下列选项中不合适的列表
'(atom1 . (atom2))
'((atom1) . atom2)
'(atom1 atom2)
(cdr '(atom1))
(cons 'atom1 '(atom2))
【问题讨论】:
标签: scheme
我想知道为什么
'((atom1) . atom2)
是下列选项中不合适的列表
'(atom1 . (atom2))
'((atom1) . atom2)
'(atom1 atom2)
(cdr '(atom1))
(cons 'atom1 '(atom2))
【问题讨论】:
标签: scheme
正确的列表可以是空列表,也可以是 cons 单元格,其中 car 指向一个数据(可能是另一个 cons 结构,例如列表),而 cdr 指向到另一个适当的列表。有关详细信息,请参阅here。在这个例子中:
'((atom1) . atom2)
atom2 不是空列表,因此它是不正确的。让我们看看其他例子:
; `(atom2)` is a list, so the whole expression is a list
'(atom1 . (atom2))
; it's a well-formed list of atoms
'(atom1 atom2)
; the `cdr` part of '(atom1) is the null list, which is also a proper list
(cdr '(atom1))
; consing an element at the head of a proper lists yields a proper list
(cons 'atom1 '(atom2))
【讨论】:
atom2 这个名字正好表明了这一点:它是一个原子。当然,如果有人命名为atom 的东西不是原子,我就没有办法知道它:)
atom2 不是一个列表,它是一个原子。它不能变成一个列表——但你可以把它放在一个列表中。这个列表是正确的:'((atom1) . (atom2))
atom2 实际上是一个符号,所以它当然不是一个列表。请记住,您的列表已被引用,因此它不可能被评估为变量引用或任何东西。
null 符号?这不是 Common Lisp。 :-) (在 Scheme 中,空列表对象不是符号。在 CL 中,nil 符号用作空列表的表示。)
'((atom1) . '(atom2 atom3 atom4)) 与 '((atom1) quote (atom2 atom3 atom4)) 相同,并且是正确的列表。但我认为您实际上是指'((atom1) . (atom2 atom3 atom4)),这也是一个正确的列表('((atom1) atom2 atom3 atom4))。
不正确的列表是任何pair 满足的地方:
(define (improper? pair)
(and (not (eq? (cdr pair) '()))
(not (pair? (cdr pair)))))
换句话说,不正确的列表是指任何一对不是另一对或空列表。
> (improper? '(atom1 . (atom2)))
#f
> (improper? '((atom1) . atom2))
#t
> (improper? '(atom1 atom2))
#f
> (improper? (cdr '(atom1)))
#f ;; (cdr '(atom1)) is not a pair - can't use my improper?
> (improper? (cons 'atom1 '(atom2)))
#f
或对任何“事物”(不仅仅是“对”)进行相反的表述:
(define (proper? thing) ;; the cdr of the last pair must be '()
(or (null? thing)
(and (pair? thing)
(proper? (cdr thing)))))
【讨论】:
cdr 中有一对不是最后一对。
improper-list? 或improper-pair? 或improper-atom? 还是什么? :) 顺便说一句,您的第一个代码没问题;只是措辞/命名有点偏离。我从未见过配对被称为“不当”。但是如果我们谈论列表,如果列表的最后一对的 cdr 不为空,则列表是不合适的?仅此而已。 :)