# tree functions daily exercise: Table

David Van Horn dvanhorn at cs.uvm.edu
Tue Jun 21 16:27:14 CEST 2005

```Xah Lee wrote:
> here's the Python spec for the Table function:
...
> References:
>
> • for a context of this message, see: http://xahlee.org/tree/tree.htm

Here is a Scheme implementation of Table.  As noted on your web page and the
Mathematica documentation, the first argument of Table "evaluates in a
non-standard way".  Thus we use Scheme macros to control the evaluation of
this expression.  The first three clauses in this syntax definition take care
to fill in the default values for i, imin, and di when they are not provided.
The fourth clause iterates over one variable constructing a list.  Notice
this is done tail-recursively.  The last clause handles the multiple variable
case by rewriting the term into a simpler form.

(define-syntax table
(syntax-rules ()
((table exp (imax))
(table exp (i 1 imax 1)))

((table exp (i imax))
(table exp (i 1 imax 1)))

((table exp (i imin imax))
(table exp (i imin imax 1)))

((table exp (i imin imax di))
(let loop ((n imin) (accum '()))
(if (< imax n)
(reverse accum)
(loop (+ n di) (cons ((lambda (i) exp) n) accum)))))

((table exp i j ...)
(table (table exp j ...) i))))

;; Examples

(table #t (0))               ;; => '()
(table #t (5))               ;; => '(#t #t #t #t #t)
(table i (i 5))              ;; => '(1 2 3 4 5)
(table i (i 2 5))            ;; => '(2 3 4 5)
(table i (i 2 5 2))          ;; => '(2 4)
(table i (i 2 6 2))          ;; => '(2 4 6)
(table (add1 i) (i 2 6 2))   ;; => '(3 5 7)
(table (- i j) (i 2) (j 2))  ;; => '((0 -1) (1 0))

(table (list i j k) (i 2) (j 100 200 100) (k 5 6))
;; =>
'((((1 100 5) (1 100 6)) ((1 200 5) (1 200 6)))
(((2 100 5) (2 100 6)) ((2 200 5) (2 200 6))))

```