Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant code for binary addition?

Tags:

scheme

racket

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?

like image 748
Racket Noob Avatar asked May 17 '26 11:05

Racket Noob


1 Answers

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))))
like image 133
Sam Tobin-Hochstadt Avatar answered May 20 '26 13:05

Sam Tobin-Hochstadt