;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-reader.ss" "lang")((modname 3-2) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) ;; A Forest is one of: ;; -- empty ;; -- (cons Tree Forest) ;; A Tree is one of: ;; -- Number ;; -- (cons Forest (cons Number (cons Forest empty))) ;; sample data (define f1 '()) (define t1 42) (define t2 (cons f1 (cons 5 (cons f1 empty)))) (define f2 (cons t2 (cons t1 (cons 2 empty)))) ;; ----------------------------------------------------------------------------- ;; VERSION 1: NON-LOCAL ;; Forest -> Number ;; add up the numbers in a forest (check-expect (sum-of-forest f1) 0) (check-expect (sum-of-forest f2) (+ 5 42 2)) (define (sum-of-forest f) (cond [(empty? f) 0] [else (+ (sum-of-tree (first f)) (sum-of-forest (rest f)))])) ;; Tree -> Number ;; add up the numbers in a tree (check-expect (sum-of-tree t1) 42) (check-expect (sum-of-tree t2) 5) (define (sum-of-tree t) (cond [(number? t) t] [else (+ (sum-of-forest (first t)) (second t) (sum-of-forest (third t)))])) ;; ----------------------------------------------------------------------------- ;; VERSION 2: LOCAL ;; Forest -> Number ;; add up the numbers in a forest (check-expect (sumF f1) 0) (check-expect (sumF f2) (+ 5 42 2)) (define (sumF f) (local (;; Forest -> Number ;; add up the numbers in a forest (define (sumF f) (cond [(empty? f) 0] [else (+ (sumT (first f)) (sumF (rest f)))])) ;; Tree -> Number ;; add up the numbers in a tree (define (sumT t) (cond [(number? t) t] [else (+ (sumF (first t)) (second t) (sumF (third t)))]))) (sumF f)))