[英]Remove Or from a list on LISP
我必須這樣做:
(or a w (or f r t) r (not p) (or (not p) a))
==> (a w f r t r (not p) (not p) a)
我已經完成了以下功能:
(defun remove-or (x)
(cond ((null x) x)
((atom x) x)
((and (listp x) (eq (first x) 'or)) (remove-or (cdr x)))
(T (cons (remove-or (first x))
(remove-or (rest x))))))
但是結果是:
(or a w (or f r t) r (not p) (or (not p) a))
==> (a w (f r t) r (not p) ((not p) a))
如何刪除“()”?
您需要更早檢查'((或...)...)之類的or-子列表,以便將其轉換為'(... ...)。
條件是:
(and (listp lst) (listp (first lst))
(eq (first (first lst)) 'or))
和變壓器:
(append (remove-or (rest (first lst)))
(remove-or (rest lst)))
因此,這使我們通過稍微修改的第三條件分支進入您的函數:
(defun remove-or (lst)
(cond ((null lst) lst)
((atom lst) lst)
((and (listp lst) (listp (first lst))
(eq (first (first lst)) 'or))
(append (remove-or (rest (first lst)))
(remove-or (rest lst))))
(t (cons (remove-or (first lst))
(remove-or (rest lst))))))
但是,這個功能不會處理一個特殊的案例:或者在一開始的名單:( 或 AB(或(或CD)E))。 但是如果有一個附加的條件分支,如((and (listp x) (eq (first x) 'or)) (remove-or (cdr x)))
我們也將刪除or
s充當變量:(ab 或 c 或 )。
因此,這種情況必須單獨處理,例如:
(defun remove-or-head (lst)
(remove-or (if (and (listp lst) (eq (first lst) 'or))
(rest lst)
lst))
將其與遞歸函數一起隱藏起來:
(defun remove-or (lst)
(labels ((remove-or-rec (lst)
(cond ((null lst) lst)
((atom lst) lst)
((and (listp lst) (listp (first lst))
(eq (first (first lst)) 'or))
(append (remove-or-rec (rest (first lst)))
(remove-or-rec (rest lst))))
(t (cons (remove-or-rec (first lst))
(remove-or-rec (rest lst)))))))
(remove-or-rec (if (and (listp lst) (eq 'or (first lst)))
(rest lst)
lst))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.