A DrRacket Programming Question

PROBLEM:

You’ve been asked to design a program having to do with all the owls
in the owlery.

(A) Design a data definition to represent the weights of all the owls.
For this problem call it ListOfNumber.
(B) Design a function that consumes the weights of owls and produces
the total weight of all the owls.
(C) Design a function that consumes the weights of owls and produces
the total number of owls.

 

Solution:

;; ListofNumber is one of:
;; -empty
;; -(cons Number ListofNumber)
;; interp. each number in the list is the weight of owl in pounds

(define L1 empty)
(define L2 (cons 60 (cons 40 empty)))

#;
(define (fn-for-lon l)
(cond [(empty? l) (…)]
[else (… (first l)
(fn-for-lon (rest l)))]))
;; template rules used:
;; -one of: 2 cases
;; -Atomic Dinstinct: empty
;; -compound: (cons Number ListofNumber)
;; -self-reference: (rest l) is ListOfNumber

;;Function
;; ListofNumber -> Number
;; produce the total weights of all in consumed list
(check-expect (sum empty) 0)
(check-expect (sum (cons 60 empty)) 60)
(check-expect (sum (cons 70 (cons 60 empty))) (+ 70 60 0))
; (define (sum l) 0) ;stub
; template used from ListofNumber
(define (sum l)
(cond [(empty? l) 0]
[else (+ (first l)
(sum (rest l)))]))

;;Function
;; ListofNumber -> Number
;; produce the number of owls in consumed wights list
(check-expect (count empty) 0)
(check-expect (count (cons 50 empty)) 1)
(check-expect (count (cons 60 (cons 50 empty))) 2)
; (define (count l) 0) ;stub
; template used from ListofNumber
(define (count l)
(cond [(empty? l) 0]
[else (+ 1
(count (rest l)))]))

 

All 6 test passed.

Leave a Reply

Your email address will not be published. Required fields are marked *