;; got-milk? takes a list of symbols and returns #t ;; if the list contains 'milk, #f otherwise ;; ::= '() ;; ::= (cons ) ;; got-milk? : -> ;; (got-milk? '()) ->-> #f ;; (got-milk? (cons 'milk '())) ->-> #t ; Template: ;(define (got-milk? l) ; (cond ; [(null? l) ...] ; [(pair? l) ...(car l) ...(got-milk? (cdr l)) ... ])) (define (got-milk? l) (cond [(null? l) #f] [(pair? l) (or (eq? 'milk (car l)) (got-milk? (cdr l)))])) ; Alternate implementation: ;(define (got-milk? l) ; (cond ; [(null? l) #f] ; [(pair? l) (cond ; [(eq? 'milk (car l)) #t] ; [else (got-milk? (cdr l))])])) (got-milk? '()) (got-milk? (cons 'milk '())) (got-milk? '(apple banana coconut)) ;;---------------------------------------- ; sum takes a list of numbers and returns their sum ;; ::= '() ;; ::= (cons ) ; sum : -> ; (sum '()) -> 0 ; (sum (cons 1 '())) -> 1 ;(define (sum l) ; (cond ; [(null? l) ...] ; [else ...(car l)... (sum (cdr l)) ... ])) (define (sum l) (cond [(null? l) 0] [else (+ (car l) (sum (cdr l)))])) ;;---------------------------------------- ; ::= ; ::= (cons ) ; ::= '() ; ct2 counts the number of symbols in an ; ct2 : -> ; (ct2 'apple) -> 1 ; (ct2 (cons 'apple 'banana)) -> 2 ; (ct2 '()) -> 0 ;(define (ct2 l) ; (cond ; [(symbol? l) ... l ...] ; [(pair? l) ...(ct2 (car l))... (ct2 (cdr l)) ...] ; [(null? l) ... ])) (define (ct2 l) (cond [(symbol? l) 1] [(pair? l) (+ (ct2 (car l)) (ct2 (cdr l)))] [(null? l) 0])) ; got-milk2? : -> ; (got-milk2? 'milk) -> #t (define (got-milk2? l) (cond [(symbol? l) (eq? 'milk l)] [(pair? l) (or (got-milk2? (car l)) (got-milk2? (cdr l)))] [(null? l) #f])) ;; milk->cola replaces every 'milk in an with 'cola ;; milk->cola : -> ;; (milk->cola 'milk) -> 'cola ;; (milk->cola (cons '() 'milk)) -> (cons '() 'cola) ;; (milk->cola '()) -> '() (define (milk->cola l) (cond [(symbol? l) (cond [(eq? 'milk l) 'cola] [else l])] [(pair? l) (cons (milk->cola (car l)) (milk->cola (cdr l)))] [(null? l) '()])) ;; replace takes an , a symbol X, and a symbol Y, and ;; replaces X with Y in ;; replace : -> ;; (replace 'milk 'milk 'cola) -> 'cola ;; (replace (cons 'apple '()) 'milk 'banana) -> (cons 'apple '()) ;; (replace '() 'x 'y) -> '() ;(define (replace sexp sym1 sym2) ; (cond ; [(symbol? sexp) ... sexp ...] ; [(pair? sexp) ...(replace (car sexp) sym1 sym2) ; ... (replace (cdr sexp) sym1 sym2) ...] ; [(null? sexp) ... ])) (define (replace sexp sym1 sym2) (cond [(symbol? sexp) (cond [(eq? sym1 sexp) sym2] [else sexp])] [(pair? sexp) (cons (replace (car sexp) sym1 sym2) (replace (cdr sexp) sym1 sym2))] [(null? sexp) '()])) ;;---------------------------------------- ; Exmaple of mutually referencing data definitions: ; ::= ; ::= ; := '() ; := (cons ) ; ... implies mutually recursive templates and functions ...