我需要帮助在dr racket的r5rs语法中对此进行编码。调整功能,使其计算前n个偶数的总和
答案 0 :(得分:3)
您没有在问题中提供足够的信息来提供准确的答案。哦 - 好吧 - 只是为了好玩,让我们看看如何使用流来解决这个问题。假设您已安装SRFI-41:
,以下内容将在R5RS下运行; import streams library
(#%require srfi/41)
; generate an infinite stream of numbers
; starting at x, with an n increment
(define (iter x n)
(stream-cons x (iter (+ x n) n)))
; compute the sum of the first n even numbers
(define (sum-even n)
(let loop ((evens (iter 0 2)) ; stream of even numbers
(acc 0) ; accumulated sum
(n n)) ; generate n numbers
(if (zero? n) ; did we generate enough numbers?
acc ; then return the accumulator
(loop (stream-cdr evens) ; else advance recursion
(+ acc (stream-car evens)) ; update accumulator
(- n 1))))) ; one less number to generate
按预期工作:
(sum-even 6)
=> 30
(= (sum-even 6) (+ 0 2 4 6 8 10))
=> #t
答案 1 :(得分:2)
与ÓscarLópez的回答一样,这是另一种基于流的实现:
(#%require srfi/41)
(define (sum-first-n-evens n)
(stream-fold + 0 (stream-take n (stream-from 0 2))))