[plt-scheme] Re: trying not to use eval - in a define-syntax
Lo, on Tuesday, October 29, Jim Witte did write:
> For list-related administrative tasks:
> http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>
> >> I want to take the value from a variable and use it as a procedure
> >> name, and have it be evaluated. I remember running across some
> >> advice in a text that using eval was *BAD*, but I am stumped on how
>
> I want to make a 'foreach' syntax which would function like map,
> except that it would (1) go in order (instead of arbitrary), (2) pass
> in the reference for each element the function is currently processing,
> and (3) be able to pass in an arbirary number of 'static' variables
> that don't change from one invocation to the other: So I could do
> something like this silly example:
It's not clear to me why you need special support for part 3. Why not
just use Scheme's support for lexical closures?
And, given that, I don't think you need any sort of syntactic support at
all. Why not just use a function?
Instead of
> (define add-index-and-constant
> (lambda (el i a)
> (+ el i a)))
>
> (foreach with-vars add-index-and-constant '(1 2 3 4) '(10))
> --> (10 13 15 17)
I'd probably write something like
(define add-index-and-constant
(lambda (a)
(lambda (elt idx)
(+ elt idx a))))
(define map-lr/index
(lambda (f lst)
(let loop ((idx 0) (lst lst))
(if (null? lst)
'()
;; Force l->r eval order
(let ([result (f (car lst) idx)])
(cons result (loop (+ 1 idx) (cdr lst))))))))
(map-lr/index (add-index-and-constant 10) '(1 2 3 4))
--> '(11 13 15 17)
No syntax involved. (Making map-lr/index tail-recursive is left as an
exercise for the reader.)
Richard