Scheme subset recursion problem using R5RS For the power function: (define (p l)
ID: 3766753 • Letter: S
Question
Scheme subset recursion problem using R5RS
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. 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?
Explanation / Answer
for this you have to write your own sorting procedure or you have to import a library like one of the SRFIs.
but for using this soring methods which need a compare function to compare to elements
we have to follow the this algorithm to do this thing is
1) if two elemnts have dufferent length then the elemtn with less legth should go first
(let ((cmp (- (length e1) (length e2))))
(cond ((negative? cmp) #t)
((positive? cmp) #f)))
2) if both are of equal length then
test both lists element by element and at any stage if elemets differ
then the list with lower element should go first
define (less-than? e1 e2)
(cond ((or (null? e1) (null? e2)) #f)
((< (car e1) (car e2)) #t)
((> (car e1) (car e2)) #f)
(else (less-than? (cdr e1) (cdr e2)))))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.