2014-10-04 87 views
-1

使用累计递归来编写一个称为update-balance的函数,该函数使用一个交易清单lot,在月初(考虑第0天)的起始余额,start-bal和a代表最低余额的非负数,min-bal。该功能在批量完成所有交易后产生银行账户的余额。累计递归drracket,累计交易

经与累计使用递归

(define (trans-val t start-bal min-bal) 
     (cond 
     [(symbol=? (trans-action t) 'withdraw) 
      (cond 
      [(>= (- start-bal (trans-amt t)) min-bal) 
      (- start-bal (trans-amt t))] 
      [else (- start-bal (+ 1 (trans-amt t)))])] 
     [else 
      (cond 
      [(>= (+ start-bal (trans-amt t)) min-bal) 
      (+ start-bal (trans-amt t))] 
      [else (+ start-bal (- (trans-amt t) 1))])])) 
+0

你的程序是不是递归的。它只是作用于一个“事务”struct't'。你也可以澄清,如果你想退出并获得小于'min-bal'的平衡,应该发生什么。在这个代码中,你只需要添加1并退出,我不确定这是你想要的。 – Rptx 2014-10-04 18:52:50

回答

0

也许是这样一个问题?

(define (update-balance lot start-bal min-bal) 
    (if (null? lot) 
     ; no more transactions to process -> return start-bal 
     start-bal 
     ; take next transaction (t), calculate new balance 
     (let* ((t (car lot)) 
      (new-bal ((if (eq? (trans-action t) 'withdraw) - +) 
         start-bal 
         (trans-amt t)))) 
     ; if new balance >= minimum balance, use that, otherwise retain previous balance 
     ; in any case, tail-recursively call update-balance to process the next transaction 
     (update-balance (cdr lot) 
         (if (>= new-bal min-bal) new-bal start-bal) 
         min-bal)))) 

测试:

> (update-balance (list (trans 'deposit 100) (trans 'withdraw 80)) 0 0) 
20 
> (update-balance (list (trans 'deposit 10) (trans 'withdraw 80)) 0 0) 
10