Inkplay_
Inkplay_

Reputation: 561

can you create local variables inside of a function that stores returned values from another function?

#lang racket

; function for calculating circle area.
(define (find-disk-area r ) (* 3.14 (* r r)))

; function for finding the ring size.
(define (find-ring-area r1 r2)
  (
     ;let((a1 (find-disk-area r1))) <- syntax error cond: bad syntax in: cond
     ;(set! (find-disk-area r1) a1) <- syntax error cond: bad syntax in: cond
     ; how do I create two local variable inside of this
     ; function so I don't need to call find-disk-area 4 times?
     cond
     [(> r1 r2) (- (find-disk-area r1) (find-disk-area r2))]
     [else (- (find-disk-area r2) (find-disk-area r1))]
     )
  )

(find-ring-area 100 90)

As you can see from above, I have to call the find-disk-area helper function 4 times. I would like to call the helper function twice, store the area of 2 circles, and then use the stored values to calculate the ring.The cond is there to make sure we subtract the smaller circle from the bigger circle. I am new to the language, and the prefix syntax style is throwing me off.

If I write it in python, the body of the find ring function would look something like:

a1 = find-disk-area(r1)
a2 = find-disk-area(r2)

if( a1 > a2 ):
    print(a1 - a2)
else:
    print(a2 - a1)

Upvotes: 1

Views: 245

Answers (1)

assefamaru
assefamaru

Reputation: 2789

You can use let to locally bind variables in your procedure. This would look as follows:

(define (find-disk-area r)
  (* pi (sqr r)))

(define (find-ring-area r1 r2)
  (let ([a1 (find-disk-area r1)]
        [a2 (find-disk-area r2)])
    (cond
      [(> a1 a2) (- a1 a2)]
      [else (- a2 a1)])))

You can also use define to the same effect, binding an identifier to the result of some expression:

(define (find-ring-area r1 r2)
  (define (find-disk-area r)
    (* pi (sqr r)))
  (define a1 (find-disk-area r1))
  (define a2 (find-disk-area r2))
  (if (> a1 a2)
      (- a1 a2)
      (- a2 a1)))

Furthermore, you can avoid defining a1 and a2 altogether by doing:

(define (find-ring-area r1 r2)
  (define (ring-area r1 r2)
    (* pi (- (sqr r1) (sqr r2))))
  (if (> r1 r2)
      (ring-area r1 r2)
      (ring-area r2 r1)))

Upvotes: 2

Related Questions