Elegant code for binary addition?
racket, scheme
Solution
Here's a new version of `add-registers` that looks somewhat nicer:
(define (add-registers xs ys)
(for/fold ([carry 0] [bs empty])
([b1 (reverse xs)] [b2 (reverse ys)])
(define-values (nb nc) (bit-add b1 b2 carry))
(values nc (cons nb bs))))
Problem
I just wrote the function add-registers for binary addition of two n-bit registers in Racket (using bit-add function as a helper): ``` (define (bit-add x y c) (values (bitwise-xor x y c) (bitwise-ior (bitwise-and x y) (bitwise-and x c) (bitwise-and y c)))) (define (add-registers xs ys) (let ([carry 0]) (values (reverse (for/list ([b1 (reverse xs)] [b2 (reverse ys)]) (let-values ([(nb nc) (bit-add b1 b2 carry)]) (set! carry nc) nb))) carry))) ``` But I found my code pretty ugly. So I wonder if this could be written more concisely and elegant?