(((a b) c) d (e (g)))At the top level, this list has three components, ((a b) c), d, and (e (f)). If we look within these components, we find there are a total of six symbols (the letters a through g). To count or otherwise process these symbols, procedures must work within sublists as well as working within the top level of the main list. As we have seen consistently, procedures in Scheme typically work recursively. Here, such procedures must apply recursion to components of lists as well as to the top-level components. Such processing is called deep recursion.
Goals: This laboratory exercise describes an example of deep recursion and provides experience applying this technique to several more examples.
Preparation: Reread section 4.3 of the textbook.
Example: Consider the problem to count the number of times a given symbol appears in a list or any of its sublists. If this task were performed by procedure count-symbol, then this procedure should give the following results:
(count-symbol 'a '(((a b) c) a (a (b)))) ===> 3 (count-symbol 'b '(((a b) c) a (a (b)))) ===> 2 (count-symbol 'd '(((a b) c) a (a (b)))) ===> 0To attack this problem, we first identify an easy case: the empty list does not contain any symbol. This observation prompts the first part of some code for count-symbol:
(define count-symbol (lambda (symbol ls) (cond ((null? ls) 0) ;;; further conditions to be determined ) ) )If we do not encounter a null list, then it is possible to follow several approaches. In one such approach, there are two main cases:
(define count-symbol (lambda (symbol ls) (cond ((null? ls) 0) ((pair? (car ls)) (+ (count-symbol symbol (car ls)) (count-symbol symbol (cdr ls)))) ((eq? symbol (car ls)) (+ 1 (count-symbol symbol (cdr ls)))) (else (count-symbol symbol (cdr ls))) ) ) )
Steps for this Lab:
(define question-2 (lambda (Ls) (cond ((null? Ls) #t) ((pair? (car ls)) (and (question-2 (car ls)) (question-2 (cdr ls)))) ((number? (car ls)) (question-2 (cdr ls))) (else #f) ) ) )
This document is available on the World Wide Web as