0

I have the following assignment.

In this implementation, you must use let-form to define local name and local procedures for PI, areac, and volumec. The procedures TotalVolume and main remain to be global.

I have the program that was created in Question 3 here:

(define PI 3.14159265)
(define (areac d)
  (* (* PI (/ d 2)) (/ d 2)))
(define (volumec d h)
  (let ((a (areac d)))
    (/ (* a h) 3)))
(define (TotalVolume)
  (let ((v1 (volumec 1 1))
        (v2 (volumec 2 2))
        (v3 (volumec 3 3))
        (v4 (volumec 4 4))
        (v5 (volumec 5 5)))
    (display (+ v1 v2 v3 v4 v5))))
(define main  
  (TotalVolume))

But now I am completely confused on how to use let-form to to change the code. I understand how let-form works, and I understand that for PI I can just use:

(let
    (
     (PI 3.14159265)
)
(body)
)

Can anyone guide me in the right direction for this problem?

Mark
  • 2,380
  • 11
  • 29
  • 49
Rakeen Huq
  • 37
  • 1
  • 5

1 Answers1

0

The key point here is that some of the definitions depend on previous definitions (for example: volumec needs areac and PI), so we need to nest the bindings and define the functions using lambdas. Here's how:

(define (TotalVolume)
  (let ((PI 3.14159265))
    (let ((areac (lambda (d) (* (* PI (/ d 2)) (/ d 2)))))
      (let ((volumec (lambda (d h) (/ (* (areac d) h) 3))))
        (let ((v1 (volumec 1 1))
              (v2 (volumec 2 2))
              (v3 (volumec 3 3))
              (v4 (volumec 4 4))
              (v5 (volumec 5 5)))
          (display (+ v1 v2 v3 v4 v5)))))))

A simpler way would be to use let*, which allows us to define bindings which depend on previously defined variables:

(define (TotalVolume)
  (let* ((PI 3.14159265)
         (areac (lambda (d) (* (* PI (/ d 2)) (/ d 2))))
         (volumec (lambda (d h) (/ (* (areac d) h) 3)))
         (v1 (volumec 1 1))
         (v2 (volumec 2 2))
         (v3 (volumec 3 3))
         (v4 (volumec 4 4))
         (v5 (volumec 5 5)))
    (display (+ v1 v2 v3 v4 v5))))
Óscar López
  • 232,561
  • 37
  • 312
  • 386