; Local binding and recursion ; you can also locally define recursive procedures... ; this is useful it we have a recursive procedure that is only used by one other ; procedure, like kernel procedures for tail-recursion, or error checking ; procedure from the previous lab ;; tail recursive version of count-this-symbol ;(define count-this-symbol ; (lambda (sym ls) ; (count-this-symbol-kernel sym ls 0))) ; ;; we pass the value 0 into sofar originally, because we have not yet seen any ;; occurences of sym ;(define count-this-symbol-kernel ; (lambda (sym ls sofar) ; (if (null? ls) ; sofar ; (if (equal? (car ls) sym) ; (count-this-symbol-kernel sym (cdr ls) (+ 1 sofar)) ; (count-this-symbol-kernel sym (cdr ls) sofar))))) ; new syntax, for command LETREC ; (letrec ; ((PROCEDURE-NAME1 PROCEDURE-DEFINITION1) ; (PROCEDURE-NAME2 PROCEDURE-DEFINITION2) ; ..... ; (PROCEDURE-NAMEn PROCEDURE-DEFINITIONn)) ; EXPRESSION) ; where the procedures are called ; now let's put count-this-symbol-kernel in a letrec ;(define count-this-symbol ; (lambda (sym ls) ; ; (letrec ; ; letrec allows us to put the definition of the kernel right inside the outer procedure ; ((kernel ; (lambda (symk lsk sofar) ; *** ; (if (null? lsk) ; sofar ; (if (equal? (car lsk) symk) ; (kernel symk (cdr lsk) (+ 1 sofar)) ; (kernel symk (cdr lsk) sofar)))))) ; ; (kernel sym ls 0)))) ; *** ; you can also use a nifty shorthand for letrecs which define one procedure ; that is called exactly once.... it's called "named let" ; we will convert the procedure above so it uses a "named let" (define count-this-symbol (lambda (sym ls) (let kernel ; binding list which sets kernel variables to their initial values ; this line is shorthand for both of the lines marked *** in the previous procedure ((symk sym) (lsk ls) (sofar 0)) ; now the guts are the same as the guts of our kernel in the letrec (if (null? lsk) sofar (if (equal? (car lsk) symk) (kernel symk (cdr lsk) (+ 1 sofar)) (kernel symk (cdr lsk) sofar)))))) ; note that this contains all the information that the previous procedures contain