简体   繁体   中英

Creating a binary counter in scheme

How would one go about creating a function increment , such that when you give it a binary number the output is the next highest binary number?

Examples:

• (increment ’(0 0 1))    returns   ’(0 1 0) 
• (increment ’(1 1 0))    returns   ’(1 1 1) 
• (increment ’(1 1 1 1))  returns   ’(0 0 0 0) 
• (increment ’(1 0 1 1 1) returns   ’(1 1 0 0 0) 

I believe the best way to go about this would be to check if the least significant digit is zero, and change it to 1 if it is. I'm not sure how to actually write that or make it a recursive program. I've only been programming in scheme for a few weeks so any help, even pseudocode, is helpful.

It's easiest to handle in little-endian form, so I suggest reversing the list, then reversing the output to put it back in big-endian form.

(define (increment lst)
  (define (go lst carry)
    (if (null? lst)
      null
      (let-values (((digit carry^)
                    (case (+ carry (car lst))
                      ((0) (values 0 0))
                      ((1) (values 1 0))
                      ((2) (values 0 1)))))
        (cons digit (go (cdr lst) carry^)))))
  (reverse (go (reverse lst) 1)))

As requested, without multiple return values:

(define (increment lst)
  (define (go lst carry)
    (if (null? lst)
      null
      (let* ((sum    (+ carry (car lst)))
             (digit  (if (= 1 sum) 1 0))
             (carry^ (if (= 2 sum) 1 0)))
        (cons digit (go (cdr lst) carry^)))))
  (reverse (go (reverse lst) 1)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM