簡體   English   中英

Lisp - 如何檢查列表是否為點對?

[英]Lisp - How can I check if a list is a dotted pair?

如何檢查 lisp 中的列表是否為點對?

CL-USER 20 : 3 > (dotted-pair-p (cons 1 2))
T

CL-USER 20 : 3 > (dotted-pair-p '(1 2))
NIL

CL-USER 20 : 3 > (dotted-pair-p '(1 2 3))
NIL

我嘗試檢查length=2是否出現錯誤:

CL-USER 28 : 1 > (= (length (cons 2 3)) 2)
Error: In a call to LENGTH of (2 . 3), tail 3 is not a LIST.

“點對符號”中的 lisp 列表類似於:

(1 . ()).

由於這是家庭作業,我會讓你得出合乎邏輯的結論。 比較

(LIST 1 2) => (1 . (2 . ()))

(CONS 1 2) => (1 . 2).

這兩者有什么不同? 您如何使用謂詞來區分它們?

記住所有正確的 lisp 列表都以空列表結尾。 問問自己如何訪問 cons 對的第二個元素? 那里的解決方案應該很清楚。

因為列表總是以空列表結尾,而一對則不然:

(listp (cdr '(1 2))) => T
(listp (cdr '(1 . 2))) => NIL
(not(listp(cdr (cons 1 2))))=> T
(not(listp(cdr (list 1 2))))=> nill

虛線對是一個缺點單元格,它的 CDR 本身不是缺點(遞歸定義)。 所以這個'(1. 2)是一個點對,但是這個'(1. ())不是,因為它只是 '(1) 的印刷表示並且與'(1)相同。

(defun dotted-pair-p (x)
  (and (consp x)
       ;; Check that CDR is not a list with LISTP
       ;; since (CONSP ()) ;;=> NIL
       ;; and the CDR of a pair can't be NIL for it
       ;; to be dotted.
       (not (listp (cdr x)))))

(dotted-pair-p '(1 . 2))            ;T
(dotted-pair-p '(1 . ()))       ;NIL

虛線列表(最后一個 cons 單元格為虛線的列表)在 Common Lisp 中由LIST*定義。 我們現在也可以使用上面的函數為它們定義一個謂詞:

(defun list*p (x)
  (dotted-pair-p (last x))) 

(list*p (list* 1 2 3 4))        ;T
(list*p (list 1 2 3 4))         ;NIL

您可以檢查列表是否點綴(以非零原子結尾):

(defun dotted-listp (l)
  (cond ((null l) nil)
        ((atom l) t)
        (t (dotted-listp (cdr l)))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM