;; An Expr is one of ;; -- Number ;; -- (make-add Expr Expr) ;; -- (make-mul Expr Expr) (define-struct add (left right)) (define-struct mul (left right)) ;; Examples 10 3 5 (make-add 1 2) (make-add (make-add 1 2) 3) (make-mul 5 10) #| TEMPLATE for Expr (define (f e) (cond [(number? e) ... e ... ] [(add? e) ... (f (add-left e)) ... (f (add-right e)) ... ] [(mul? e) ... (f (mul-left e)) ... (f (mul-right e)) ... ])) |# ;; count-numbers: Expr -> Number ;; the number of numbers in e (define (count-numbers e) (cond [(number? e) 1 ] [(add? e) (+ (count-numbers (add-left e)) (count-numbers (add-right e))) ] [(mul? e) (+ (count-numbers (mul-left e)) (count-numbers (mul-right e))) ])) ;; Examples (= (count-numbers 10) 1) (= (count-numbers (make-add 1 2)) 2) (= (count-numbers (make-add (make-add 1 2) 3)) 3) (= (count-numbers (make-mul 1 2)) 2) (= (count-numbers (make-mul (make-mul 1 2) 3)) 3) ;; sum: Expr -> Number ;; sum up all the numbers in e (define (sum e) (cond [(number? e) e ] [(add? e) (+ (sum (add-left e)) (sum (add-right e))) ] [(mul? e) (+ (sum (mul-left e)) (sum (mul-right e))) ])) ;; Examples (= (sum 10) 10) (= (sum (make-add 1 2)) 3) (= (sum (make-add (make-add 1 2) 3)) 6) (= (sum (make-mul 1 2)) 3) (= (sum (make-mul (make-mul 1 2) 3)) 6) ;; contains: Expr Number -> Boolean ;; whether e contains n (define (contains e n) (cond [(number? e) (= e n) ] [(add? e) (or (contains (add-left e) n) (contains (add-right e) n) ) ] [(mul? e) (or (contains (mul-left e) n) (contains (mul-right e) n) ) ])) ;; Examples (contains 10 10) (not (contains 5 10)) (contains (make-add 1 2) 2) (not (contains (make-add 1 2) 3))