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?
>>3
Yes. Also, before I posted this I hadn't really looked into the function beyond its definition. I can see that I could probably make it simpler by just repetitively using the two input thing instead of redefining the next in terms of the previous one (which I suppose ends up being a repetition of the 2 input anyways).
Name:
Anonymous2012-09-14 15:57
(define-syntax xor
(syntax-rules ()
((_)
#f)
((_ #f e ...)
(xor e ...))
((_ #t e ...)
(not (xor e ...)))))
Name:
Anonymous2012-09-14 16:03
Fixed version: (define-syntax xor
(syntax-rules ()
((_)
#f)
((_ #f e ...)
(xor e ...))
((_ _ e ...)
(not (or e ...)))))