[英]Scheme: power set recursion, printing in sorted order using R5RS
Scheme subset recursion problem 方案子集递归问题
For the power function: 对于幂函数:
(define (p l)
(define (n next)
(if (null? next)
'()
(cons (car next)
(cons (cons (car l) (car next))
(n (cdr next))))))
(if (null? l)
'(())
(n (p (cdr l)))))
I would like to print all sets in increasing order of number of elements, and also same size in sorted order ONLY USING R5RS . 我只想使用R5RS按元素数量的升序打印所有集合,并按排序顺序打印相同的大小。 For example,
例如,
If I define a list like this 如果我定义这样的列表
(define list3 (list '1 '2 '3))
and call the funtion, 并调用该功能,
(p'(1 2 3))
My output is 我的输出是
(() (1) (2) (1 2) (3) (1 3) (2 3) (1 2 3))
But I want to print out like: 但是我想像这样打印出来:
(() (1) (2) (3) (1 2) (1 3) (2 3) (1 2 3))
Also, for the case of 另外,对于
(p'(1 2 3 4))
My output is : 我的输出是:
(()
(1)
(2)
(1 2)
(3)
(1 3)
(2 3)
(1 2 3)
(4)
(1 4)
(2 4)
(1 2 4)
(3 4)
(1 3 4)
(2 3 4)
(1 2 3 4))
But I want 但我想要
(()
(1)
(2)
(3)
(4)
(1 2)
(1 3)
(1 4)
(2 3)
(2 4)
(3 4)
(1 2 3)
(1 2 4)
(1 3 4)
(2 3 4)
(1 2 3 4))
How can I make correct output? 如何进行正确的输出?
There's an easy alternative: use your current implementation of a power set procedure and sort the output as required: 有一个简单的选择:使用当前的电源设置过程实现并根据需要对输出进行排序:
(define (compare s1 s2)
(let ((cmp (- (length s1) (length s2))))
(cond ((negative? cmp) #t)
((positive? cmp) #f)
(else (less-than? s1 s2)))))
(define (less-than? s1 s2)
(cond ((or (null? s1) (null? s2)) #f)
((< (car s1) (car s2)) #t)
((> (car s1) (car s2)) #f)
(else (less-than? (cdr s1) (cdr s2)))))
But here's the catch - we need a sort
procedure, and that's not part of R5RS: 但这很重要-我们需要一个
sort
过程,并且这不是R5RS的一部分:
(sort (p '(1 2 3)) compare)
=> '(() (1) (2) (3) (1 2) (1 3) (2 3) (1 2 3))
Of course, it's not that hard to implement your own sorting procedure that receives a procedure for comparing the elements. 当然,这并不难实现接收,用于比较要素的程序自己的排序方法。 Or if you're allowed, you can import it from an existing library, such as one of the SRFIs.
或者,如果允许,则可以从现有库(例如SRFI之一)中将其导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.