0

我正在尝试编写一个将元素添加到给定 powerset 的每个元素的函数。不管它总是将 (null pset) 评估为真。我不明白为什么。

这是我到目前为止所拥有的:

(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))))) 
4

1 回答 1

0

首先,请注意,在终端情况下,您应该返回一个空列表,因为在递归中处理了幂集的所有元素,我们应该假设幂集始终是列表列表,每个列表代表一个集合(事实上​​,空集的幂集至少包含一个元素,即空集本身)。

因此,由于 powerset 是一个非空列表,向 powerset 添加新元素的任务可以通过将结果添加到 powerset 的每个列表中来解决,列表和列表的副本与元素添加。

在这两种情况下,“添加”的意思是:得到一些东西并返回一个新的东西,并使用返回的值,否则,正如 Rainer 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))))
于 2015-10-08T12:21:29.727 回答