[特别是读一本有关函数式编程和方案(以及Racket)的书时,我碰巧遇到了一个练习,陈述如下:`
"Write a function 'rp' which takes, as an argument, a list 'lp' of pairs '(a . n)',
where 'a' is either a symbol or a number and 'n' is a natural number,
and which returns the list of all the lists, whose elements are the 'a's defined by
the pairs in 'lp', each one appearing exactly 'n' times."
出于某种原因,这确实是个谜,但它的基本要求是包含n乘以数字/符号a的列表的所有不同排列的列表。
例如:[[(rp '((a . 2) (b . 1))]] = '((a a b) (a b a) (b a a))
[生成排列而忽略distinct
部分,是相当容易的,因为有一个相对简单的递归定义:
The list of permutations of an empty list, is a list containing an empty list.
The list of permutations of 3 elements a b c is a list containing the lists of all permutations of
a and b where, for each one, c has been inserted in all possible positions.
我翻译了以下球拍代码:
(define permut
(lambda(ls)
(if(null? ls) '(())
(apply append
(map (lambda(l) (insert_perm (car ls) l))
(permut (cdr ls)))))))
(define insert_perm
(lambda(x ls)
(if(null? ls) (list (list x))
(cons (cons x ls)
(map (lambda(l) (cons (car ls) l))
(insert_perm x (cdr ls)))))))
这有效,但不会返回不同的排列。在我看来,考虑重复项似乎要复杂得多。我看不到简单排列情况的简单修改吗?解决方案完全不同吗?任何帮助,将不胜感激。
; When your input is '((a 2) (b 1))
; Or something like that. it can be (a . 2) or vector('a 2)
; change input become normal list -> L = '(a a b)
; just use permutations -> (permutations input-L)
; If you don't want repeate just remove repeate. -> (remove-duplicates output-List)
; Done.
更新2