【问题标题】:Racket scheme define constant in function球拍方案在函数中定义常量
【发布时间】:2013-04-20 13:03:18
【问题描述】:

我是计划的初学者。我有这样的功能:

(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)]

                            )

在这个函数中,我计算了 (sqrt (+ (* A A) (* B B))) 几次。我想在这个函数的开头只计算一次这个表达式(使常量或变量),但我不知道如何......

【问题讨论】:

  • 请正确缩进,圆括号() 应该像其他编程语言中的花括号{} 一样匹配。另外,请参阅下面我的回答,了解完成您所要求的其他可能的方法

标签: scheme racket


【解决方案1】:

您有多种选择,对于初学者,您可以使用 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)]))

如果使用其中一种高级教学语言,请使用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)])))

或者使用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)])))

无论如何,请注意为变量选择一个好的名称(在本例中为distance)是多么重要,并在表达式的其余部分引用该名称。此外,值得指出的是,使用的语言(初级、高级等)可能会限制可用的选项。

【讨论】:

    【解决方案2】:

    看看 let 表单(及其相关的表单 let*、letrecletrec* )。 好的描述是http://www.scheme.com/tspl4/start.html#./start:h4http://www.scheme.com/tspl4/binding.html#./binding:h4

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      • 2022-07-27
      • 2013-03-03
      相关资源
      最近更新 更多