CSC151, Class 18: List Recursion, Continued Overview: * tally-skips * Lab * Reflection Notes: * Read Numeric Recursion * How to make the Delete key work the way you want. * Lab writeup 2 is optional * List of topics updated. * Grading writeup 1. Done soon. * Our Tuesday visitors return. * No, you won't finish the lab. Tally-Skips (tally-skips (list 'hop 'skip 'jump 'and 'skip 'again)) => (tally-skips (list 'skip 'jump 'and 'skip 'again)) => (+ 1 (tally-skips (list 'jump 'and 'skip 'again))) => (+ 1 (tally-skips (list 'and 'skip 'again))) => (+ 1 (tally-skips (list 'skip 'again))) => (+ 1 (+ 1 (tally-skips (list 'again)))) => (+ 1 (+ 1 (tally-skips (list)))) => (+ 1 (+ 1 0)) => (+ 1 1) => 2 ; Purpose: ; count the number of times the symbol 'skip ; appears in lst. (define tally-skips (lambda (lst) (cond ; If the list is empty [Cite: KP] ((null? lst) 0) ; If the car of the list is equal to ; skip [Cite: Many voices] ((eq? (car lst) 'skip) ; Count that one ; Count how many skips remain ; Add 'em together. (+ 1 (tally-skips (cdr lst)))) ; If the first one isn't skip (else (tally-skips (cdr lst)))))) ; Another version: Using a helper procedure to ; keep a running count of the number of skips ; seen so far (define skip-tallier (lambda (lst skips) (display (list 'skip-tallier lst skips)) (newline) (cond ((null? lst) skips) ((eq? (car lst) 'skip) ; Continue, after ... (skip-tallier ; Drop the first element of the list (cdr lst) ; Add 1 to skips (+ 1 skips))) (else (skip-tallier (cdr lst) skips))))) (define dan-counts-skips (lambda (lst) (skip-tallier lst 0))) ---------------------------------------- How do you say "Is there only one element in this list? (if (null? (cdr lst))