Scheme 中的倍数之和

Sum of Multiples in Scheme

所以我对 Scheme 和整个函数式编程都很陌生。 我正在尝试编写一个程序来查找 1000 以下的所有 3 或 5 的倍数的总和。 这是我到目前为止的尝试:

(define (sum-of-multiples n)
; Start = 0, End = n, Sum = 0.
(get-sum 0 n 0)
)

; A recursive loop that starts at 0 and ends with given n (1000).
(define (get-sum start end sum)
   (cond
   ; Stopping case.
   ((= start end) sum)
   ; If start counter is divisible by 3, add to sum.
   ((= (remainder start 3) 0) (get-sum (+ start 1) end (+ start sum)))
   ; If start counter is divisible by 5, add to sum.
   ((= (remainder start 5) 0) (get-sum (+ start 1) end (+ start sum)))
   ; Otherwise just increment start counter.
   (get-sum (+ start 1) end sum))
)

(display (sum-of-multiples 1000))
(display " ")

我不确定目前我的代码出现问题是因为 Scheme 语法问题还是我试图通过递归来解决问题。 因为这两件事我都不擅长。

当我 运行 此代码时,我只显示“0”。

如果能帮助我找出并解决我的错误,那就太好了。

谢谢!

cond格式为:

(cond (<condition> <expr>)
       .
       .
      (else <expr>))

在您的代码中没有 elseget-sum 函数(经过一些重新格式化)应该是:

(define (get-sum start end sum)
   (cond
      ((= start end) sum)
      ((= (remainder start 3) 0)
       (get-sum (+ start 1) end (+ start sum)))
      ((= (remainder start 5) 0)
       (get-sum (+ start 1) end (+ start sum)))
      (else
       (get-sum (+ start 1) end sum))))

通过此修复,您的代码显示 233168。我没有检查你的算法,但这个结果看起来比 0 更好:)

您遗漏了 "all other cases" 案例中的 else;应该是

(else (get-sum (+ start 1) end sum))

试图解释你从哪里得到 0:

cond 子句的形式为 (condition expression),因此您的条件为 get-sum
就像else一样,这个条件永远不会为假。

条件后面还有一个隐含的begin,所以你的相当于

(else (begin (+ start 1) end sum))

其结果是 begin 块中最后一个表达式的值,即 sum

因为第一次达到那个条件时sum是0,所以结果是0。