What I'm trying to do is take two lists and add them together like each list is a whole number.
(define (reverse lst)
(if (null? lst)
'()
(append (reverse (cdr lst))
(list (car lst)))))
(define (apa-add l1 l2)
(define (apa-add-help l1 l2)
(cond ((and (null? l1) (null? l2)) '())
((null? l1) (list (+ (apa-add-help '() (cdr l2)))))
((null? l2) (list (+ (apa-add-help (cdr l1) '()))))
((>= (+ (car l1) (car l2)) 10)
(append (apa-add-help (cdr l1) (cdr l2))
(list (quotient (+ (car l1) (car l2)) 10))
(list (modulo (+ (car l1) (car l2)) 10)))) ;this is a problem
(else (append (apa-add-help (cdr l1) (cdr l2))
(list (+ (car l1) (car l2)))))))
(apa-add-help (reverse l1) (reverse l2)))
(apa-add '(4 7 9) '(7 8 4))
>'(1 1 1 5 1 3)
I know that the problem is revolved around my recursion, I reversed the order of the lists to allow for easier process, however I can't seem to understand how to add my modulo value (carried over value) to the next object in the list. How can I do this?
reverse
is already defined in Racket so there's no need to redefine it.I have rewritten your code for a version that is clearer (to me, at least):
such as
car0
andcdr0
are functions that help me to continue processing empty lists as a list of zeroes.I introduced a new variable, carry, which is used to carry a value from iteration to iteration, just as you do it manually.
EDIT 1
The
named let
is equivalent to the following code:EDIT 2
The non tail-recursive version would be