-3

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

2 Answers2

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
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
    or an equally inadmissible `(define (sum-fne n) (* n (- n 1)))`. :) – Will Ness Sep 09 '13 at 08:42
  • 1
    +1 for _not_ reinventing the wheel :P – Óscar López Sep 09 '13 at 21:49
  • @Ó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