#lang racket (require rackunit) (provide subst count-occurrences) ;; ------------------------------------------------------------------------- ;; EXAMPLE : subst, using program derivation ;; on the original version from Session 10 ;; ------------------------------------------------------------------------- (define (subst new old slist) (if (null? slist) '() (cons (if (symbol? (first slist)) ;; (if (eq? (first slist) old) ;; Here is new ;; the second (first slist)) ;; substitution. (subst new old (first slist))) ;; (subst new old (rest slist))))) (check-equal? (subst 'd 'b '(a b c a b c d)) '(a d c a d c d)) (check-equal? (subst 'a 'b '((a b) (((b g r) (f r)) c (d e)) b)) '((a a) (((a g r) (f r)) c (d e)) a)) ;; ------------------------------------------------------------------------- ;; EXERCISE: count-occurrences, using program derivation ;; on the original version from Session 10 ;; ------------------------------------------------------------------------- (define count-occurrences (lambda (s slist) (if (null? slist) 0 ;; slst is empty (+ (if (symbol? (first slist)) ;; slst is a cons (if (eq? s (first slist)) 1 0) ;; first is a symbol (count-occurrences s (first slist))) ;; first is an slist (count-occurrences s (rest slist))) ))) ;; rest is always slist (check-equal? (count-occurrences 'a '(a b c)) 1) (check-equal? (count-occurrences 'a '(((a be) a ((si be a) be (a be))) (be g (a si be)))) 5) ; -------------------------------------------------------------------------