#11: C-style Loops

Tagged as challenge

Written on 2018-01-30

Part 1

Implement a C-style for-loop without using another explicit imperative looping construct.

(for ((<var> <init>) <condition> <post-loop-thing>)

For example:

 (for ((i 0) (< i 10) (set! i (+ 1 i)))
  (display i)

which would print 0 through 9. Unlike C, i's scope is limited.

Part 2

Now extend for so you can do (for (<var> in <list>) …) to iterate over lists. This is (almost) equivalent to Common Lisp's dolist macro.

Part 3

Generalize the results of Part 2 so that the user can "program" the for-loop with iteration semantics of any data type. As an example of what this may mean, though you might do it differently, is to have a table of predicates, like so in Common Lisp:

(defvar *for-loop-extensions*
         ; predicate    ???
        '((listp        ???)
          (vectorp      ???)

;; for-loop should now work with at least
;; lists and vectors.
(for (i in #(1 2 3))
  (print i))

I've put ??? so as to not spoil what they could be.

Unless otherwise credited all material copyright © 2010–2018 by Robert Smith