I'm making a function which adds big numbers together manually (no library function) and I'm having some trouble capturing the result to display. I simply display back '(). Here's a little back ground of how it should work: If I pass (big-add1 '(999) '(456) 0), I should return '(455 1). If I pass (big-add1 '(999 234 681) '(456) 0) I should return '(455 235 681). But I've had no success displaying anything other than the empty list so far. Here's my code right now:
(define (big-add1 x y co)
(cond
;; If both lists are empty, the return value is either 0 or the carryover value.
[(and (= 0 (length x)) (= 0 (length y)))
(if (= co 0) '() (list co))]
[(= 0 (length x)) (big-add1 (list co) y 0)]
[(= 0 (length y)) (big-add1 x (list co) 0)]
[else
(cond(< (length x) (length y)) (big-add1 y x 0)) ;reverse the order of parameters
(append (list(+ (modulo (car x) 10) (modulo (car x) 10) co))) ;trying to construct a result
(if(>(+ (modulo (car x) 10) (modulo (car x) 10) co) 9)
(letrec ([co 1]) co) ;if addition produces a double digit number set carryover value
(letrec ([co 0]) co));if addition produces a single digit number
(if(or(> (car x) 10) (> (car y) 10)) ;we got down to single digits
(big-add1(append(list(quotient (car x) 10)) (cdr x)) (append(list(quotient (car y) 10)) (cdr y)) co)
(big-add1 (cdr x) (cdr y) co))
]
))
(big-add1 '(999) '(456) 0)
(big-add1 '(999 234 681) '(456) 0)
Bonus question: If anyone is feeling up for it, I can see in debug mode that co is not getting changed to 1 when the sum is greater than 10. It seems to execute the line, but not actually change it. Could anyone clarify what is going on? I super new to this, so if anyone has any suggestions on how to simplify it, please feel free to let me know. I would really appreciate it. Thank you for your time.
append
doesn't mutate. Uselet
to bind names to intermediate results. Then combine those. – Dan D.(let ((x 1)) (let ((x (+ x 1))) x))
evaluates to 2. The second let shadows the binding of the first. – Dan D.