CS2613/tests/Final/Q1 Racket/balance.rkt

22 lines
793 B
Racket
Raw Permalink Normal View History

2022-12-20 21:49:28 -04:00
#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))