2013-10-23 50 views
1

我想在保留列表格式的同時在方案中一起添加兩個數字(來自列表)。但是,當用於計算的數字加上大於或等於10的數字時,我會得到不希望的結果。例如:「添加任意精度數字」在方案

(define (reverse lst) 
    (if (null? lst) 
     '() 
     (append (reverse (cdr lst)) 
      (list (car lst))))) 

(define (apa-add lst1 lst2) 
    (cond ((null? lst1) lst2) 
    ((null? lst2) lst1) 
    ((>= (+ (car lst1) (car lst2)) 10) 
    (append (apa-add (cdr lst1) (cdr lst2)) 
     (list (quotient(+ (car lst1) (car lst2)) 10)) 
     (list (modulo (+ (car lst1) (car lst2)) 10)))) 
     (else 
     (append (apa-add (cdr lst1) (cdr lst2)) 
     (list (+ (car lst1) (car lst2))))))) 

(apa-add (reverse '(4 4 5)) (reverse'(3 5 8))) 

回報

'(7 9 1 3) 

如何修改我的代碼來解決這個問題?我想使用let聲明,因此我可以將(quotient (+ (car lst1) (car lst2)) 10)的評估添加到下一個調用的(list (+ (car lst1) (car lst2))),但我無法考慮如何執行此操作。

+0

您的示例中期望的結果是什麼? – uselpa

+1

你想要一個程序來執行與進位算法的手加法,是嗎?你想要回報是'(8 0 3)是嗎? – WorBlux

+0

是的,這是我想要的輸出。 –

回答

1

將此變爲尾部呼叫簡化了一些事情。

(define (apa-add lst1 lst2) 
    (let loop ((carry 0) (L1 (reverse lst1)) (L2 (reverse lst2)) (sum '())) 
    (cond ((and (null? l1) (null? l2)) 
      (if (zero? carry) sum (cons carry sum))) 
      ((null? L1) 
      (loop (quotient (+ carry (car l2)) 10) 
        '() 
        (cdr L2) 
        (cons (modulo (+ carry (car l2)) 10) sum))) 
      ((null? L2) 
      (loop (quotient (+ carry (car l1)) 10) 
        (cdr l1) 
        '() 
        (cons (modulo (+ carry (car l1)) 10) sum))) 
      (else 
      (loop (quotient (+ carry (car l1) (car l2)) 10) 
        (cdr l1) 
        (cdr l2) 
        (cons (modulo (+ carry (car l1) (car l2)) 10) sum))))))    



(apa-add (list 4 4 5) (list 3 5 8)) 

;Value 4: (8 0 3) 

可能不會太難轉換爲n元函數。

(define (apa-add . Lists) 
    (define (cdrs-no-null L) 
       (cond ((null? L) '()) 
        ((null? (cdar l)) (cdrs-no-null (cdr L))) 
        (else (cons (cdar l) (cdrs-no-null (cdr l)))))) 
    (let loop ((carry 0) (Lists (map reverse Lists)) (sum '())) 
      (if (null? Lists) 
       (if (zero? carry) sum (cons carry sum)) 
       (loop (quotient (fold + carry (map car Lists)) 10) 
        (cdrs-no-null Lists) 
        (cons (modulo (fold + carry (map car Lists)) 10) sum))))) 

(apa-add (list 4 4 5) (list 3 5 8) (list 1 0 2 7)) 

;Value 11: (1 8 3 0) 

(apa-add (list 4 4 5) (list 3 5 8)) 

;Value 12: (8 0 3)