22 lines
793 B
Racket
22 lines
793 B
Racket
#lang racket
|
|
(define (balance lst)
|
|
(define (helper lst counter)
|
|
(cond
|
|
[(empty? lst) counter] ;;base case
|
|
[(list? (first lst)) (helper (rest lst) counter)] ;;unwrap list
|
|
[(eq? (first lst) 'debit) (helper (rest lst) (- counter last))] ;;if debit subtract the amount
|
|
[(eq? (first lst) 'credit) (helper (rest lst) (+ counter last))] ;;if credit add the amount
|
|
[else (helper (rest lst) counter)]
|
|
)
|
|
)
|
|
(helper lst 0)
|
|
)
|
|
|
|
;; Racket
|
|
(module+ test
|
|
(require rackunit)
|
|
(check-equal? (balance (list (list 'credit 5))) 5)
|
|
(check-equal? (balance (list '(debit 5))) -5)
|
|
(check-equal? (balance '((debit 11) (credit 3))) -8)
|
|
(check-equal? (balance '((debit 3) (credit 5))) 2)
|
|
(check-equal? (balance '((debit 5) (credit 23) (debit 23) (credit 5))) 0)) |