为什么我必须用列表将 n 包围两次才能获得正确的结果?

Why do i have to surround n with list twice to get the proper result?

(define (all-sublists buffer n)
  (cond ((= n 0) n)
        ((all-sublists (append buffer (list (list n)) (map (lambda (x) (append (list n) x)) buffer)) (- n 1)))))

结果如下所示:

(all-sublists '((3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)) 0)

当n周围只有一个列表时:

(define (all-sublists buffer n)
  (cond ((= n 0) n)
        ((all-sublists (append buffer (list n) (map (lambda (x) (append (list n) x)) buffer)) (- n 1)))))

结果得到一个点对:

(all-sublists '(3 2 (2 . 3) 1 (1 . 3) (1 . 2) (1 2 . 3)) 0)

不是你有 "to surround n with list twice to get the proper result",事实是你的代码有几个问题,首先:cond 的最后一个条件应该以 else 开头,并且您使用的 append 不正确。如果我没理解错的话,你只需要一个列表的幂集:

(define (powerset aL)
  (if (empty? aL)
      '(())
      (let ((rst (powerset (rest aL))))
        (append (map (lambda (x) (cons (first aL) x))
                     rst)
                rst))))

像这样:

(powerset '(1 2 3))
=> '((1 2 3) (1 2) (1 3) (1) (2 3) (2) (3) ())