0

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. 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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jieun Chon
  • 139
  • 1
  • 10

1 Answers1

1

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 (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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386