[racket] Looping with look-behind and look-forward

From: Neil Van Dyke (neil at neilvandyke.org)
Date: Sun May 27 22:29:54 EDT 2012

I do see a plausible potential feature addition to the standard sequence 
iterators like "for/fold".  (I don't need it myself, since I don't use 
the iterators, but I can see that other people might.)

I have occasionally implemented and used a list-processing "map" or 
"fold" that provides the preceeding and following neighbors, and 
wondered how common a need for such a function would be.  (I consider 1 
nearest neighbor and N nearest neighbors to be separate cases.)

I think a problem here is that we have these fancy iterators, and 
programmers who haven't learned how to do things the old-fashioned way 
when the fancy iterators don't fit their problem.  One solution is for 
the iterators to expand their bag of tricks.  (An alternate solution is 
for people to be discouraged from using the iterators until they know 
how to do the same thing without the iterators, but I don't expect 
anyone to agree to that. :)

To add the 1-nearest neighbor to "for/fold, for example, I suppose that 
one would actually only need to provide a 1-element lookahead feature, 
since we already have the accumulator terms that can be used for 
previous neighbor.  1-element lookahead sound plausibly basic to me, 
especially when the iterator otherwise makes that harder than it should 
be.  Looks like one could just add another "FOR-CLAUSE" production:

FOR-CLAUSE ::= (THIS-ID #:next (NEXT-ID NEXT-VOID-INIT) SEQ-EXPR)

If someone wanted to do this, looks like it could actually be 
implemented in a macro that expands to the standard "for/fold".  (I 
think it could even be done in "syntax-rules", to win a bar bet.)  But I 
suppose a better way would be to modify the canonical "for/fold" 
implementation, if indeed the feature was wanted in the canonical 
implementation.

Neil V.


Posted on the users mailing list.