Formatting SCHEME递归完美数(初学者,希望容易修复)

Formatting SCHEME递归完美数(初学者,希望容易修复),formatting,scheme,racket,perfect-numbers,Formatting,Scheme,Racket,Perfect Numbers,我的完美数函数有问题。代码的目的是确定这个数是否是一个完美数,也就是说它等于它的除数之和。例:6。我的代码有问题。以下是我的功能: (define (is-perfect x) (define (divides a b) (= (modulo b a) 0)) (define (sum-proper-divisors y) (if (= y 1) 1 (if (divides y x) (+ y (sum-proper-di

我的完美数函数有问题。代码的目的是确定这个数是否是一个完美数,也就是说它等于它的除数之和。例:6。我的代码有问题。以下是我的功能:

(define (is-perfect x)
  (define (divides a b) (= (modulo b a) 0))
  (define (sum-proper-divisors y)
    (if (= y 1)
        1
        (if (divides y x)
            (+ y (sum-proper-divisors (- y 1)))
        (if (= x 1)
            #f
            (= (sum-proper-divisors (- x 1)
                                    x)))))))

你差点就成功了!不过,还有几个问题。首先,
sum property divisions
中缺少一个case:询问
y
是否为一,以及
(除以yx)
,但是如果
y
不除以
x
,会发生什么情况

第二个问题是,最后一个
if
表达式必须在两个helper过程的定义之外,目前它位于
求和适当除数的内部。正确缩进代码将更容易发现此类错误

这是一个正确的解决方案,因为这看起来像是家庭作业,我让你填一下:

(define (is-perfect x)
  (define (divides a b)
    (= (modulo b a) 0))
  (define (sum-proper-divisors y)
    (cond ((<= y 1)
           1)
          ((divides y x)
           (+ y (sum-proper-divisors (- y 1))))
          (else
           <???>))) ; what goes in here?
  (if (= x 1)
      #f
      (= (sum-proper-divisors (- x 1)) x)))
(定义(是完美的x)
(定义(划分a和b)
(=(模b a)0))
(定义(和适当的除数y)

(cond)((如果您已经知道这是“可能是括号问题”,那么您应该能够自己解决它。Racket要求我将后面的括号保持在无穷循环的x=0,可能删除If并将
(=y 1)1)
更改为
((很抱歉,但我的建议似乎引入了一个bug,我没有注意到0)“变成”这样的完美数字。if谓词应该是