CS2613/tests/Q1/quiz1.rkt
2022-10-05 10:16:46 -03:00

27 lines
1004 B
Racket

#lang racket
(define (sum lst) ;define sum function
(define (helper lst sum) ;setup tail recursive helper
(cond ;conditions for recursion
[(empty? lst) 0] ;base case
[else (if ;case for if the list item is a number
(number? (first lst)) ;if the item is a number
(helper ((rest lst) (+ sum (first lst)))) ;call the helper function with the rest of the list and add to sum
(helper (rest lst) sum)) ;error case if it is not a number
]))
(helper lst 0)) ;first recursive call
;my attempet to use match, was not going well
;(match lst
; [`() 0]
; [(number? head tail ...) (+ sum head)
(module+ test
(require rackunit)
(check-equal? (sum `()) 0)
(check-equal? (sum `(1 2)) 3)
(check-equal? (sum `(1 2 "buckle my shoe")) 3)
(check-equal? (sum `(-1 -2)) -3) ;test for negative numbers
(check-equal? (sum `(-1 `(1 2) -2)) 3) ;test for recursive lists
(check-equal? (sum `(0.1 0.2)) 0.3) ;test for floating point numbers
)