views:

825

answers:

4

Is there a for loop or for each loop in Scheme ?

I've been searching around and found there is a keyword "every" but the scheme compiler language I'm using does not have this function pre-build in. This is what it suppose to do, it can be find here

(define (first-letters sent)
  (every first sent))

> (first-letters '(here comes the sun))
(H C T S)

How can I re-write the every function ? using other pre-defined function. The language I'm using is in the DrScheme - Essentials of Programming Languages (3rd ed)

I tried all the pre-installed compiler in DrScheme none of them can compile the every function.

Any ideas ?

+2  A: 

This could be the answer of your question. Map function, takes a function and list(-s) as arguments, applies function to elements of list, returns the results.

Toms Mikoss
+4  A: 

You are looking for map, although you probably would like to know that Scheme also has for-each. map does exactly what you want with every. It does something to each item in the list, returning a new list of the results.

You could even say

(define every map)

You can get your first function by writing

(define (first symbol)
  (string->symbol (string (string-ref (symbol->string symbol) 0))))

This is bad Scheme style, though. It looks like ancient Lisp from the 60s or 70s, back before strings were in the language. Anyway, Now you can say

(map first '(here comes everybody))
=> (h c e)


for-each does some kind of side effect to each item in the list:

(define initials (map first '(here comes everybody)))
(for-each display initials)
=> hce
Nathan Sanders
The definition of `first` would be slightly better as `(string->symbol (substring (symbol->string symbol) 0 1))`.
Cirno de Bergerac
A: 

Depends which Scheme you're looking at. Apart from "for-each" and "map" mentioned above (which are part of the various standards, hence present in all real Schemes), you can find impelementation-specific extensions. For example, PLT scheme has a whole slew of such forms, which you can read about here.

offby1
+1  A: 

This is an addition to Nathan's post, which is the best answer for you right now...

If you ever move over to the scheme or scheme/base module languages, you will gain access to PLT's army of for iterators. These look a bit more like the "for each" loops that are common in other languages. Search for for in the docs:

(define (first symbol)
  (string->symbol (string (string-ref (symbol->string symbol) 0))))

(for/list ([symbol (in-list '(here comes everybody))])
  (first symbol))

=> '(h c e)
Dave G