2015-10-08 40 views
0

我正在嘗試編寫一個函數,將一個元素添加到給定powerset的每個元素。無論它總是評估(null pset)爲真。我不明白爲什麼。如何將對象添加到LISP中列表的每個元素?

這是我到目前爲止有:

(defun addxtopowerset(x pset) 
    (cond 
     ((null pset) (list x '())) ; If the powerset is null, display x and NIL. 
     ;;First display a list combining x and the first item of pset. Then display the first item of pset itself. Then recursively call the function passing the rest of pset as a parameter. 
     (T (list 'x (car pset))(list (car pset)) 
     (addxtopowersetch x (cdr pset))))) 
+3

那些'LIST'操作2和3。他們在做什麼?結果在哪裏?目前看起來結果直接進入了數字涅。。 –

回答

0

首先要注意的是,在終端的情況下,你應該返回一個空列表,因爲在該冪的所有元素被處理的遞歸,我們應該假定一個powerset是總是列表的一個列表,它們每個代表一個集合(實際上,一個空集合的powerset至少包含一個元素,空集合本身)。

因此,由於powerset是一個非空列表,向powerset添加一個新元素的任務可以通過添加結果來解決,對於powerset的每個列表,列表和副本都可以解決添加元素的列表。

在這兩種情況下,「增加」是指:得到的東西和一個新東西,使用返回的值,否則,如賴Joswig記「的結果直接進入數字必殺技」。換句話說,在遞歸的情況下,你的函數必須在遞歸調用的結果中添加兩個值,列表和添加元素的新列表。所以,這裏的功能是:

(defun addxtopowerset(x pset) 
    (if (null pset) 
     nil 
     (append (list (car pset) (cons x (car pset))) 
       (addxtopowerset x (cdr pset))))) 

最後,這裏幾個定義函數,第一個與高階函數mapcan的替代辦法:

(defun addxtopowerset(x pset) 
    (mapcan (lambda(y) (list y (cons x y))) pset)) 

,第二個用loop

(defun addxtopowerset(x pset) 
    (loop for y in pset append (list y (cons x y)))) 
+0

完美,非常感謝!我認爲append,list和cons之間的區別最讓我困惑,比如什麼時候把一個嵌套在另一個裏面。 –

相關問題