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

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Sun May 27 10:38:22 EDT 2012

2012/5/27 Harry Spier <vasishtha.spier at gmail.com>:
> Is the "for" form a macro?  And if so how difficult would it be to
> make a new form "for-with-look-around" that had built in look-back and
> look-ahead operators (next x) (prior x) (  next?) (prior?).
> So you could do something like:
> ((define (running-average-of-3 l)
>   (for-with-look-around
>    ([x (in-list l)])
>    (unless? (or (prior?) (next?))
>                 (displayln (/ (+ x (prior x) (next x)) 3))))))
> From a functional programming perspective is building a form like this
> a bad idea?

It is a fine idea.
Here is variation on the idea.

(define (in-triples l)
  (define (sublists xs)
    (if (empty? xs)
        (cons xs (sublists (rest xs)))))
  (define (triple xs) (take xs 3))
  (sequence-map triple (drop-right (sublists l) 2)))

(define (running-average-of-3 l)
  (for ([t (in-triples l)])
    (match-define (list x y z) t)
    (displayln (/ (+ x y z) 3))))

(running-average-of-3 '(1 2 3 4 5 6))

Posted on the users mailing list.