Name: Anonymous 2012-09-14 15:09
So in my intro to computer science class with SICP scheme, we have to write an xor function. Is there a simpler way to do this than what I have (I only used and, or, and equal)
(define (xor2 a b)
(if (or a b)
(if (and a b)
#f
#t)
#f))
(define (xor3 a b c)
(if (and a b c)
#t
(if (or a b c)
(if (and a b)
(xor2 a b)
(if (and a c)
(xor2 a c)
(if (and b c)
(xor2 b c)
#t)))
#f)))
(define (xor4 a b c d)
(if (or a b c d)
(if (and a b c d)
#f
(if (or a b c)
(if (equal? a #f)
(xor3 b c d)
(if (equal? b #f)
(xor3 a c d)
(if (equal? c #f)
(xor3 a b d)
(xor3 a b c))))))
#f))
This works, but is there a way to simplify it, and maybe generalize it to n elements?
(define (xor2 a b)
(if (or a b)
(if (and a b)
#f
#t)
#f))
(define (xor3 a b c)
(if (and a b c)
#t
(if (or a b c)
(if (and a b)
(xor2 a b)
(if (and a c)
(xor2 a c)
(if (and b c)
(xor2 b c)
#t)))
#f)))
(define (xor4 a b c d)
(if (or a b c d)
(if (and a b c d)
#f
(if (or a b c)
(if (equal? a #f)
(xor3 b c d)
(if (equal? b #f)
(xor3 a c d)
(if (equal? c #f)
(xor3 a b d)
(xor3 a b c))))))
#f))
This works, but is there a way to simplify it, and maybe generalize it to n elements?