我刚刚编写了函数add-registers,用于在Racket中添加两个n位寄存器(使用bit-add函数作为帮助器):
(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)))
但我发现我的代码非常难看。所以我想知道这是否可以写得更简洁和优雅?
答案 0 :(得分: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))))