我正在寫一個函數,它接受一個列表並返回參數的排列列表。生成列表的排列
我知道如何通過使用一個函數來刪除一個元素,然後遞歸地使用該函數來生成所有的排列。我現在有,我想用下面的函數問題:
(define (insert-everywhere item lst)
(define (helper item L1 L2)
(if (null? L2) (cons (append L1 (cons item '())) '())
(cons (append L1 (cons item L2))
(helper item (append L1 (cons (car L2) '())) (cdr L2)))))
(helper item '() lst))
此功能將插入項目到列表中的每一個可能的位置,如下所示:
(insert-everywhere 1 '(a b))
將獲得:
'((1 a b) (a 1 b) (a b 1))
我該如何使用此函數來獲取列表的所有排列?
我現在有:
(define (permutations lst)
(if (null? lst)
'()
(insert-helper (car lst) (permutations (cdr lst)))))
(define (insert-helper item lst)
(cond ((null? lst) '())
(else (append (insert-everywhere item (car lst))
(insert-helper item (cdr lst))))))
但這樣做(permutations '(1 2 3))
只是返回空列表'()
。
我看到的,所以每個答案的車當前列表插入到先前列表的所有排列的所有位置中。 如何將insert-everywhere函數應用於之前列表的每個排列? – 2012-02-16 08:42:42
@EricMercer,聽起來像一個輔助功能的好工作。 – 2012-02-16 10:34:48
對不起,你能澄清一下嗎?我仍然不確定該怎麼辦? – 2012-02-17 00:59:02