开发者

"for each" or "every" keywords in Scheme

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 ?


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


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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜