2
votes

I am beginer to scheme. I have function like this:

(define (getRightTriangle A B N) (
                            cond
                              [(and (integer? (sqrt (+ (* A A) (* B B)))) (<= (sqrt (+ (* A A) (* B B))) N))
                               (list (sqrt (+ (* A A) (* B B))) A B)
                               ]
                              [else (list)]

                            )

In this function I compute (sqrt (+ (* A A) (* B B))) several times. I want to compute this expression only once in beginning of this function (make constant or variable) but I don't know how...

2
Please indent correctly, pairs of parenthesis () should not be matched as if they were curly braces {} in other programming languages. Also, see my answer below for other possible ways to accomplish what you're asking - Óscar López

2 Answers

3
votes

You have a couple of options, for starters you could use a define special form like this:

(define (getRightTriangle A B N)
  (define distance (sqrt (+ (* A A) (* B B))))
  (cond [(and (integer? distance) (<= distance N))
         (list distance A B)]
        [else (list)]))

Or use local if using one of the advanced teaching languages:

(define (getRightTriangle A B N)
  (local [(define distance (sqrt (+ (* A A) (* B B))))]
    (cond [(and (integer? distance) (<= distance N))
           (list distance A B)]
          [else (list)])))

Or use one of the let special forms for creating a local variable, which IMHO is the cleanest way:

(define (getRightTriangle A B N)
  (let ((distance (sqrt (+ (* A A) (* B B)))))
    (cond [(and (integer? distance) (<= distance N))
           (list distance A B)]
          [else (list)])))

Anyway, notice how important it is to choose a good name for the variable (distance in this case), and refer to that name in the rest of the expression. Also, it's worth pointing that the language in use (Beginner, Advanced, etc.) might restrict which options are available.

1
votes

Take a look at the let form (and its associated forms let*, letrec and letrec*). Good descriptions are http://www.scheme.com/tspl4/start.html#./start:h4 and http://www.scheme.com/tspl4/binding.html#./binding:h4.