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.

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

Dani AI

Generated

The do form needs two parts: a list of loop bindings (each as (var init step)), and a termination clause that returns the final result. The original attempt used (car L) as an init for x (that will blow up when L is empty because in do inits are evaluated before the termination test). was on the right track: initialize an accumulator to 0 and advance a list variable each loop — just fix the typo (suma) and provide the missing binding.

A simple, clear do version that avoids mutating the original argument:

(define (sumiteration L)
  (do ((total 0)
       (rest L (cdr rest)))
      ((null? rest) total)
    (set! total (+ total (car rest)))))

How it works: total starts at 0; rest starts as the input L. Before each iteration Scheme checks ((null? rest) total); if true it returns total. Inside the body car is safe because rest is known non-empty; after the body rest is updated to (cdr rest) for the next iteration. This keeps the loop local and readable — prefer a fresh rest name instead of changing the function argument L. If do is not recognized in your DrScheme language level, switch to an R5RS/Racket language level or use a simple recursion or fold alternative.

Recommended Answers

All 6 Replies

Did you mean to post this in CompSci?

yea my bad.

Moved...

delete one of the threads since i posted it here. doesn't matter which one.

some one please help I am really confused!! :(

(define (sumiteration L)
(do ((sum 0)
)
((null? L) suma)
(set! sum (+ sum (car L)))
(set! L (cdr L))
)
)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.