lesson 04 lists of lists of lists
TRANSCRIPT
1
Lists of Lists of Lists of ...
CS 5010 Program Design Paradigms “Bootcamp”
Week 03, Lesson 4
Lists of Lists of ... strings
"alice""bob""carole"("alice" "bob")(("alice" "bob") "carole")("alice" (("alice" "bob") "dave") "eve")
Data Definition
An S-expression of Strings (SoS) is either-- a String-- a List of SoS's
A List of SoS's (LoSS) is either-- empty-- (cons SoS LoSS)
This is mutual recursion
SoS LoSS
defined in terms of
defined in terms of
Mutually Recursive Data Definitions
• One task, one function• So: one function per data definition• Here, functions come in pairs• Write the contracts and purpose statements
together, or• Write one, and the other one will appear as a
wishlist function
Template: functions come in pairs
;; sos-fn : SoS -> ??(define (sos-fn s) (cond [(string? s) ...] [else (loss-fn s)]))
;; loss-fn : LoSS -> ??(define (loss-fn los) (cond [(empty? los) ...] [else (... (sos-fn (first los)) (loss-fn (rest los)))]))
occurs-in?;; occurs-in? : Sos String -> Boolean;; returns true if the given string occurs somewhere
in the given sos.;; occurs-in-loss? : Loss String -> Boolean;; returns true if the given string occurs somewhere
in the given loss.
Examples/Tests(check-expect (occurs-in? "alice" "alice") true)(check-expect (occurs-in? "bob" "alice") false)
(check-expect (occurs-in? (list "alice" "bob") "cathy") false)
(check-expect (occurs-in? (list (list "alice" "bob") "carole") "bob") true)
(check-expect (occurs-in? (list "alice" (list (list "alice" "bob") "dave") "eve") "bob") true)
See book re list vs. cons
The Code(define (occurs-in? sos str) (cond [(string? sos) (string=? sos str)] [else (occurs-in-loss? sos str)]))
(define (occurs-in-loss? loss str) (cond [(empty? loss) false] [else (or (occurs-in? (first loss) str) (occurs-in-loss? (rest loss) str))]))
Finger Exercises;; number-of-strings : Sos -> Number;; number-of-strings-in-loss : Loss -> Number;; returns the number of strings in the given sos or
loss.
;; characters-in : Sos -> Number;; characters-in-loss : Loss -> Number;; returns the total number of characters in the
strings in the given sos or loss.
Summary
• Trees of structures occur all the time• Mutually recursive data definitions• Mutual recursion in the data definition leads to mutual
recursion in the template• Mutual recursion in the template leads to mutual
recursion in the code• Study the tests: – always ask: how could a program pass the tests and still be
wrong?– always ask: how could a program fail the tests and still be
correct?