#lang racket (require rackunit) (provide subst count-occurrences) ; -------------------------------------------------------------------------- ; VERSION 3: subst, using program derivation on Version 2 ; -------------------------------------------------------------------------- ; ORIGINAL CODE ; ;(define subst ; (lambda (new old slist) ; (if (null? slist) ; '() ; (cons (subst-symbol-expr new old (first slist)) ; (subst new old (rest slist)))))) ; ;(define subst-symbol-expr ; (lambda (new old se) ; (if (symbol? se) ; (if (eq? se old) new se) ; (subst new old se)))) ; STEP 1: replace the name with the lambda it names ; ;(define subst ; (lambda (new old slist) ; (if (null? slist) ; '() ; (cons ( (lambda (new old se) ;; ; (if (symbol? se) ;; Here is ; (if (eq? se old) new se) ;; the first ; (subst new old se) )) ;; substitution. ; new old (first slist)) ; (subst new old (rest slist))) ))) ; ; STEP 2: replace the application of the lambda with its body (define subst (lambda (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 3: count-occurrences, using program derivation on Version 1 ; ------------------------------------------------------------------------- (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))) ))) (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) ; -------------------------------------------------------------------------