Tuesday, 11 December 2012

Exercise 187: Create test suites for the following two functions:


Exercise 187: Create test suites for the following two functions:
; Lon -> Lon
; add 1 to each number on l
(define (add1* l)
  (cond
    [(empty? l) false]
    [else
     (cons (add1 (first l))
           (add1* (rest l)))]))
; Lon -> Lon
; add 5 to each number on l
(define (plus5 l)
  (cond
    [(empty? l) false]
    [else
     (cons (+ (first l) 5)
           (plus5 (rest l)))]))
Then abstract over them. Define above two functions in terms of the abstraction as one-liners and use the existing test suites to confirm that the revised definitions work properly. Finally, design a function that subtracts 2 from each number on a given list.


I had to fix the above functions to do this exercise - the empty case is returning false in the book which will make the cons fail as you can't cons a list to false.

Test Cases


; simple happy test - all numbers should be increased by one
(check-expect (add1* '(1 2 3))
              '(2 3 4))

; test empty list returns empty
(check-expect (add1* empty)
              empty)


; simple happy test - all numbers should be increased by five
(check-expect (plus5 '(1 2 3))
              '(6 7 8))

; test empty list returns empty
(check-expect (plus5 empty)
              empty)


; My abstraction - allow them to pass in the size of the increment
; Number, Lon -> Lon
(define (inc* amount l)
  (cond
    [(empty? l) empty]
    [else
     (cons (+ (first l) amount)
           (inc* amount (rest l) ))]))


; Lon -> Lon
; add 1 to each number on l
(define (add1* l)
   (inc* 1 l))

; Lon -> Lon
; add 5 to each number on l
(define (plus5 l)
  (inc* 5 l))

Part Two

 Define a function that subtracts 2 from each member of a list.

; a function that subtracts 2 from each member of a list
; Lon -> Lon
(define (minus2 l)
  (inc* -2 l))

; happy test
(check-expect (minus2 '(5 7 9))
              '(3 5 7))

No comments:

Post a Comment