How to program this in R5RS?

476 views Asked by At

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

There are 2 answers

2
Óscar López On

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
3
C. K. Young On

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))))