;; ----------------------------------------------------------------------- ;; | | ;; | FILE : map-nlist.rkt | ;; | AUTHOR : Eugene Wallingford | ;; | CREATION DATE : 2024/02/20 | ;; | | ;; | DESCRIPTION : Solutions to the two warm-up exercises in | ;; | Session 11. We revisit structural recursion, | ;; | mutual recursion, and program derivation. | ;; | | ;; | REQUIRES : Uses Rackunit for testing. | ;; | | ;; ----------------------------------------------------------------------- #lang racket (require rackunit) ;; ------------------------------------------------------------------------- ;; map-nlst (mutual recursion) ;; ------------------------------------------------------------------------- (define (map-nlist f nlst) (if (null? nlst) '() (cons (map-numexp f (first nlst)) (map-nlist f (rest nlst))))) (define (map-numexp f numexp) (if (number? numexp) (f numexp) (map-nlist f numexp))) (check-equal? (map-nlist add1 '(1 4 9 16 25 36 49 64)) '(2 5 10 17 26 37 50 65)) (check-equal? (map-nlist even? '(1 (4 (9 (16 25)) 36 49) 64)) '(#f (#t (#f (#t #f)) #t #f) #t)) (check-equal? (map-nlist sqr '(1 (4 (9 (16 25)) 36 49) 64)) '(1 (16 (81 (256 625)) 1296 2401) 4096)) ;; ------------------------------------------------------------------------- ;; simple example (program derivation) ;; ------------------------------------------------------------------------- (define (2n-plus-1 n) (add1 (* 2 n))) (check-equal? (2n-plus-1 15) ; substitution 1: lambda for name ((lambda (n) (add1 (* 2 n))) 15)) (check-equal? ((lambda (n) ; substitution 2: body for lambda app (add1 (* 2 n))) 15) (add1 (* 2 15))) ;; ------------------------------------------------------------------------- ;; map-nlst (program derivation) ;; ------------------------------------------------------------------------- ;; (define (map-nlist f nlst) ;; (if (null? nlst) ;; '() ;; (cons (if (number? (first nlst)) ;; (f (first nlst)) ;; (map-nlist f (first nlst))) ;; (map-nlist f (rest nlst))))) ;; ;; (check-equal? (map-nlist add1 '(1 4 9 16 25 36 49 64)) ;; '(2 5 10 17 26 37 50 65)) ;; ;; (check-equal? (map-nlist even? '(1 (4 (9 (16 25)) 36 49) 64)) ;; '(#f (#t (#f (#t #f)) #t #f) #t)) ;; ;; (check-equal? (map-nlist sqr '(1 (4 (9 (16 25)) 36 49) 64)) ;; '(1 (16 (81 (256 625)) 1296 2401) 4096)) ;; -------------------------------------------------------------------------