Need help with a function in DrScheme

Discussion of Scheme and Racket
Post Reply
lotrsimp12345
Posts: 1
Joined: Sun Mar 07, 2010 10:08 pm

Need help with a function in DrScheme

Post by lotrsimp12345 » Sun Mar 07, 2010 10:09 pm

I can write the recursion version correctly need help with writing a do loop in DrScheme.

After the do loop the variable x is sent to car L intially and then is updated to first element of everything but first element in list.

Code: Select all


(Toggle Plain Text)
(define (sumiteration L)
  (do ((x (car L) (car(cdr L))))
    ((null? L))
    (set! sum (+ sum x)))
)


griffinish
Posts: 1
Joined: Sat Apr 17, 2010 8:46 pm

Re: Need help with a function in DrScheme

Post by griffinish » Sat Apr 17, 2010 9:07 pm

The direct answer might be:

Code: Select all

(define (sumiteration someList)
  (do ((sum 0)
       (L someList (cdr L)))
    ((null? L) sum)
    (set! sum (+ sum (car L)))))
1) There was a sum referenced in the (set! sum (+ sum x)) that was not previously defined.
2) Nothing advanced the list L.

For a reasonably short input list, you might:

(apply + your-list-of-numbers)

It may also be of interest to use srfi/1 reduce which won't have a problem with large lists.

(require srfi/1)
(reduce + 0 your-list-of-numbers)

Post Reply