累积递归drracket,总计交易

时间:2014-10-04 18:18:12

标签: racket

使用累积递归来编写一个名为update-balance的函数,该函数使用一个事务列表,批次,月初的起始余额(被认为是第0天),start-bal和一个非负数字代表最低余额,最小值。该函数在完成批次中的所有交易后生成银行账户余额。

使用累积递归有问题

(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))])]))

1 个答案:

答案 0 :(得分: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