[plt-scheme] looping?

From: Danny Yoo (dyoo at hkn.eecs.berkeley.edu)
Date: Mon Jun 5 21:34:26 EDT 2006


On Mon, 5 Jun 2006, Mike wrote:

> I know there is intended a lot of recursion for scheme, but is there 
> looping? The REPL construct isn't recursive (my guess). How do you loop?

Hi Mike,

I'm not quite sure I understand why the REPL being recursive or not would 
matter.  Could you explain more?


In any case, here's an example of a "loop":

;;;;;;;;;;;;;;;;;;;;;;
(let loop ([i 0])
   (when (< i 10)
      (printf "~a~n" i)
      (loop (add1 i))))
;;;;;;;;;;;;;;;;;;;;;;

This uses a "named" loop that allows us to write a simple recursive 
function.  Here, loop starts off with zero, and we increment till we hit 
10.


If we find that we use this kind of construction a lot, we can 
capture this pattern as a function:

;;;;;;;;;;;;;;;;;;;;;;;;;;
> (define (repeat f n)
     (let loop ([i 0])
       (when (< i n)
         (f i)
         (loop (add1 i)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;

Once we have this, we can write "loops" that don't look like they're using 
recursion.


;;;;;;;;;;;;;;;;;;;;;;;;;;
> (define (print-number x)
     (printf "~a~n" x))
>
> (repeat print-number 10)
0
1
2
3
4
5
6
7
8
9
;;;;;;;;;;;;;;;;;;;;;;;;;;


Generally, though, structures will often already define some convenient 
functions for doing an operation on every element in that structure.  For 
example, if we need to transform every element in a list of things, we can 
use a *map*:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
> (define (square x) (* x x))
>
> (map square (list 3 1 4 1 5 9 2 6))
(9 1 16 1 25 81 4 36)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


The cookbook recipe on "Looping Constructs" should be helpful:

     http://schemecookbook.org/view/Cookbook/IdiomLoopingConstructs


Best of wishes!


Posted on the users mailing list.