I need help coding this in the syntax of r5rs in dr racket. Adapt the function so that it computes the sum of the first n even numbers
Asked
Active
Viewed 461 times
-3
-
2Adapt _what_ function? what have you tried so far? edit the question and post the missing code! – Óscar López Sep 08 '13 at 23:47
2 Answers
3
You didn't provide enough information in the question to give a precise answer. Oh well - just for fun, let's see how to solve this using streams. The following will work under R5RS, assuming that you have SRFI-41 installed:
; 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
It works as expected:
(sum-even 6)
=> 30
(= (sum-even 6) (+ 0 2 4 6 8 10))
=> #t

Óscar López
- 232,561
- 37
- 312
- 386
-
@jozefg kabooom! but seriously, if OP didn't specify the problem ... – Óscar López Sep 09 '13 at 02:47
-
2
In the same spirit as Óscar López's answer, here's another stream-based implementation:
(#%require srfi/41)
(define (sum-first-n-evens n)
(stream-fold + 0 (stream-take n (stream-from 0 2))))

C. K. Young
- 219,335
- 46
- 382
- 435
-
3
-
1
-
@ÓscarLópez If it's any consolation at all, I've had to become _very_ familiar with SRFI 41 since I [ported it to Guile](http://git.savannah.gnu.org/cgit/guile.git/log/module/srfi/srfi-41.scm) (with much thanks to [Mark H Weaver](http://stackoverflow.com/users/2007219/mark-h-weaver) for his outstanding review comments, which helped fine-tune the library into the form you see today). – C. K. Young Sep 09 '13 at 23:03