Created
August 27, 2013 02:30
-
-
Save sillykelvin/6349027 to your computer and use it in GitHub Desktop.
Add two numbers presented as two lists, an exercise in Lisp-cn google group.
See https://groups.google.com/forum/#!topic/lisp-cn/AVEjxh0A5r0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(define (list-add lst1 lst2) | |
(define (iter a1 a2 carry ret) | |
(cond ((and (null? a1) (null? a2)) | |
(if carry | |
(append ret '(1)) | |
ret)) | |
((null? a1) | |
(if carry | |
(iter '(1) a2 #f ret) | |
(append ret a2))) | |
((null? a2) | |
(if carry | |
(iter a1 '(1) #f ret) | |
(append ret a1))) | |
(else (let ((r (+ (car a1) | |
(car a2) | |
(if carry 1 0)))) | |
(if (>= r 10) | |
(iter (cdr a1) | |
(cdr a2) | |
#t | |
(append ret (list (- r 10)))) | |
(iter (cdr a1) | |
(cdr a2) | |
#f | |
(append ret (list r)))))))) | |
(iter lst1 lst2 #f '())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment