Question: Procedural Abstraction Consider the following five functions: (define add (lambda (sexpr) (cond ((null? sexpr) 0) ((pair? sexpr) (+ (add (car sexpr)) (add (cdr sexpr)))) (else

Procedural Abstraction

Consider the following five functions:

(define add (lambda (sexpr) (cond ((null? sexpr) 0) ((pair? sexpr) (+ (add (car sexpr)) (add (cdr sexpr)))) (else sexpr)))) (define copy (lambda (sexpr) (cond ((null? sexpr) ()) ((pair? sexpr) (cons (copy (car sexpr)) (copy (cdr sexpr)))) (else sexpr)))) (define size (lambda (sexpr) (cond ((null? sexpr) 0) ((pair? sexpr) (+ (size (car sexpr)) (size (cdr sexpr)))) (else 1)))) (define depth (lambda (sexpr) (cond ((null? sexpr) 0) ((pair? sexpr) (add1 (max (depth (car sexpr)) (depth (cdr sexpr))))) (else 0)))) (define count (lambda (pred sexpr) (cond ((null? sexpr) 0) ((pair? sexpr) (+ (count pred (car sexpr)) (count pred (cdr sexpr)))) ((pred sexpr) 1) (else 0))))

These functions can be used as follows:

> (add '((1 . 2) . (3 . 4))) 
10
> (copy '(a b c d))
(a b c d)
> (size '(a b c d))
4
> (depth '((1 . 2) . (3 . 4)))
2
> (count even? '((1 . 2) . (3 . 4)))
2 

Demonstrate your mastery of procedural abstraction by defining a function fold-tree which abstracts the pattern of the five functions. When you are finished, use fold-tree to defined

  • Give a definition of depth.
  • Give a definition of count.

Hint: You may not be able to make count fit the pattern because it has an extra case and takes an extra argument. You can curry count and use count-c to implement count. You can use a helper function to combine the last two cases and rewrite count using the helper-function. These two tricks will make it look more like the others.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Accounting Questions!