[BULK] [plt-scheme] Multiple loops

From: Stephen Bloch (sbloch at adelphi.edu)
Date: Tue Mar 31 14:26:38 EDT 2009

On Mar 31, 2009, at 1:29 PM, aditya shukla wrote:

> My question here is are there loops in scheme or recursion is used  
> in all the cases and is there is a design rule for multiple loops?

Excellent question.  Yes, Scheme has several powerful looping  
constructs; look up "iterations" in the Help Desk.  Recursion is more  
"typical" of the Scheme-programming idiom, but a professional Scheme  
programmer would know the looping constructs as well.  And you can  
frequently avoid doing either one by using one or more of the  
"abstraction" functions like map, foldl, foldr, filter, apply, etc.   
Programmers coming from other languages to Scheme often use a loop  
(sometimes even an integer-indexed loop) where it's really not  
necessary; read the solutions Matthias just posted, and even if those  
aren't exactly the problem you needed to solve, they should give you  
some good ideas for how a Scheme programmer would solve the problem.

The design rule for multiple loops is similar to the design rules  
you've seen already: the shape of the data determines the shape of  
the code.  If you're given a data object which is a collection of  
objects, you'll probably want to "do something to each element of the  
collection", and a loop is a natural way to do this.  If you're given  
several such objects, you'll probably want several such loops.

Of course, that gets you through the clean, elegant problems; things  
get messier in the real world, but a lot of the ideas are the same.

Stephen Bloch
sbloch at adelphi.edu

Posted on the users mailing list.