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

Viewed 27

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

1 Answers

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))
Related