Elegant code for binary append?
I just wrote the add-registers functions to binary add two n-bit registers in Racket (using the add bits 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 to be pretty ugly. So I wonder if this can be written more succinctly and elegantly?
+3
Racket Noob
source
to share
1 answer
The new version add-registers
looks a little nicer here:
(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))))
+5
Sam Tobin-Hochstadt
source
to share