[plt-scheme] Iterating through days of the week

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Wed May 2 07:45:00 EDT 2007

Looping in Scheme is different from looping in ordinary languages.

In general a loop is the application of an action (print, increase by  
1, etc) to a lot of pieces of data that are collected in one compound  
data (vector, list, tree, etc). If you are comfortable with functions  
consuming functions, this suggests something like this:

  ??? loop ( action, compound-data, other-arguments, ... )

The ??? stands for the type that such a "loop" can return. A  
performance constraint tends to be that loops consume only yeah much  
space. For "linear" compound-data, this usually means "constant"  
space. (For "tree" data, I suspect we should demand "linear" space,  
etc).

Ordinary languages allow only VOID in the place of ???. This forces  
the programmer to communicate values from within action to the  
outside of the loop via assignment (set!).

Functional languages allow any type for ???. Thus you can find a  
large variety of "loop" functions in such languages:

(define days-of-week-by-number (build-list 7 add1)) ;; loops over  
0 ... 6 and creates the list 1 ... 7

(for-each (lambda (d) (printf "day of week: ~s\n" d)) days-of-week-by- 
number) ;; what you expect, returns void

(define days-of-week-by-letter (map integer->char days-of-week-by- 
number)) ;; translate numbers into (funky) letters

(define sum (foldl + 0 days-of-week-by-number)) ;; add up the digits  
needed to represent days of week (why not?))

All of these are "looping" thingies.

But as someone already said, take a look at HtDP though look at  
21-23. -- Matthias




Posted on the users mailing list.