3

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?

0

1 Answer 1

6

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))))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.