Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the difference between using COND and IF in regards to Lamba/map?


(define (subset set)
    (display set)
    (cond
      ((null? set) '() )
      (else
       (append (subset (cdr set))
                   (map (lambda (subset) (cons (car set) subset))
                         (subset (cdr set)))))
     )
  )
  
 (define (power-set set)
    (display set)
    (if (null? set) '(())

             (append (power-set (cdr set))
                   (map (lambda (power-set) (cons (car set) power-set))
                         (power-set (cdr set))))))
  
(subset '(a b c))

(power-set '(a b c))

I’m new to Scheme, and I’m trying to understand the concepts. This is an example of two scheme functions that returns the powerset when given a list. One function one using cond and the other using if. The one using cond returns ‘() while the one using if returns the power set. I don’t understand how these two examples produce different outputs.

Any input would be great!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The two functions return different values for the (null? set) case. The first one returns an empty list, the second one returns a list of one element – itself an empty list. Change the first one to do the same and you get the same output:

(define (subset set)
  (cond
   ((null? set) '(()))
   (else
    (append (subset (cdr set))
            (map (lambda (subset) (cons (car set) subset))
                 (subset (cdr set)))))))

 (define (power-set set)
   (if (null? set)
       '(())
       (append (power-set (cdr set))
               (map (lambda (power-set) (cons (car set) power-set))
                    (power-set (cdr set))))))

(subset '(a b c)) ; (() (c) (b) (b c) (a) (a c) (a b) (a b c))
(power-set '(a b c)) ; (() (c) (b) (b c) (a) (a c) (a b) (a b c))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading