简体   繁体   English

球拍方案定义功能常数

[英]Racket scheme define constant in function

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 (+ (* AA) (* BB))) several times. 在此函数中,我多次计算(sqrt(+(* AA)(* BB)))。 I want to compute this expression only once in beginning of this function (make constant or variable) but I don't know how... 我只想在此函数的开头(使常量或变量)仅计算一次该表达式,但是我不知道如何...

You have a couple of options, for starters you could use a define special form like this: 您有两个选择,对于初学者,您可以使用如下define特殊形式:

(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: 如果使用高级教学语言之一,则使用local语言:

(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: 或使用let特殊形式之一创建局部变量,恕我直言,这是最干净的方法:

(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. 无论如何,请注意为变量选择一个好名字(在这种情况下为distance )并在表达式的其余部分中使用该名字是多么重要。 Also, it's worth pointing that the language in use (Beginner, Advanced, etc.) might restrict which options are available. 另外,值得指出的是,所使用的语言(入门,高级等)可能会限制可用的选项。

Take a look at the let form (and its associated forms let *, letrec and letrec *). 看一下let形式(及其关联的形式let *, letrecletrec *)。 Good descriptions are http://www.scheme.com/tspl4/start.html#./start:h4 and http://www.scheme.com/tspl4/binding.html#./binding:h4 . 很好的描述是http://www.scheme.com/tspl4/start.html#./start:h4http://www.scheme.com/tspl4/binding.html#./binding:h4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM