Let's review the new design recipe for lists (and other recursive data
definitions). We'll use Bubba-serve? as an example, and finish
writing the function.
1. Data Definition
;; A list-of-symbol is either
;; - empty, or
;; - (make-lst name los)
;; where name is a symbol and los is a list-of-symbol
(define-struct lst (first rest))
;; examples:
empty
(make-lst 'Mike
(make-lst 'Patty
(make-lst 'Bubba
empty)))
2. Contract, Purpose, Header
;; Bubba-serve? : list-of-symbol -> bool
;; determine whether Bubba is a mechanic on the list
(define (Bubba-serve? a-los) ...)
3. Test cases
(Bubba-serve? empty) = false
(Bubba-serve? (make-lst 'Mike
(make-lst 'Patty
(make-lst 'Bubba
empty)))) = true
(Bubba-serve? (make-lst 'Mike
(make-lst 'Patty
empty))) = false
4. Template, including identifying natural recursion
;; Bubba-serve? : list-of-symbol -> bool
;; determine whether Bubba is a mechanic on the list
(define (Bubba-serve? a-los)
(cond [(empty? a-los) ...]
[(lst? a-los) ...(first a-los)
...(Bubba-serve? (rest a-los))...]))
5. Body
;; Bubba-serve? : list-of-symbol -> bool
;; determine whether Bubba is a mechanic on the list
(define (Bubba-serve? a-los)
(cond [(empty? a-los) false]
[(lst? a-los) (cond [(symbol=? 'Bubba (first a-los)) true]
[else (Bubba-serve? (rest a-los))])]))
Consider the answer to each case separately. E.g., you don't need
to think about the answer to the lst? case when defining the answer
for the empty? case.
The inner cond can be simplified, but it is better to initially
write it as a cond, because you thinking of it as a conditional.
Simplify it to an "or", if you find that easier to understand.
Do NOT simplify the outer cond, because it should follow the
data definition.
6. Test
;------------
Let's look at another example, using the same template.
;; count-services : list-of-symbol -> number
;; count how many times this plane has been serviced
(define (count-services a-los)
(cond [(empty? a-los) 0]
[(lst? a-los) (add1 (count-services (rest a-los)))]))
Note that this example does not use (first a-los) because we don't
care who the individual mechanics were.
There is no counter or accumulator. To understand how the final
answer is calculated, use the stepper.