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

Issue

This Content is from Stack Overflow. Question asked by Anon


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



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


This Question was asked in StackOverflow by Anon and Answered by Shawn It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?