Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Scheme Xor

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?

Name: Anonymous 2012-09-15 17:22

>>19 here, scratch that, this version is more feature-complete, better looking and accepts a shitton of parameters:

#lang racket

(define xor
  (lambda bools
   
    (define (xor-helper res lst)
      (if (null? lst)
          res
          (xor-helper (not (eq? res (car lst)))
                      (cdr lst))))
   
    (if (foldl (lambda (a res)
                 (and res (boolean? a)))
               #t
               bools)
        (xor-helper (car bools)
                    (cdr bools))
        (raise `(xor -- Non-boolean elements in parameters: ,bools)))))



R6RS needs some fucking fuck shit SRFI to use fucking fold. So I used Racket instead.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List