2012-04-10 79 views
3

我剛寫的函數添加寄存器爲二進制加法的球拍兩個n位寄存器(使用位添加功能作爲輔助):二進制加法的優雅代碼?

(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))) 

但是我發現我的代碼很醜陋。所以我想知道這是否可以寫得更加簡潔和優雅?

回答

5

這裏是add-registers的新版本看起來有點更好:

(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))))