[racket] Call by Name
On 11/27/12 2:39 PM, J. Ian Johnson wrote:
> If you don't need to dispatch on name at runtime, you can write a macro for this and use format-id to construct the identifier naming the function. Otherwise you would need to use eval, which is highly inadvisable.
>
> #lang racket
> (require (for-syntax racket/syntax))
> (define-for-syntax ((call-fns-with-base base start end) stx)
> (syntax-case stx ()
> [(_) #`(begin #,@(for/list ([n (range start end)])
> (with-syntax ([name (format-id base "~a~a" base n)])
> #`(name))))]))
> (define-syntax call-fns (call-fns-with-base #'test 1 1000))
> (call-fns)
>
> ;(untested)
> -Ian
This is a slight variation on Ian's suggestion. It uses a macro (id-in
name n m) that constructs a list consisting of the elements namen ...
namem-1.
#lang racket
(require (for-syntax racket/syntax))
(define-syntax (id-in stx)
(syntax-case stx ()
[(id-in name i j)
(with-syntax ([(id ...)
(for/list ([n (in-range (syntax->datum #'i)
(syntax->datum #'j))])
(format-id stx "~a~a" #'name n))])
#'(list id ...))]))
(define (f1) 1)
(define (f2) 2)
(define (f3) 3)
(map (λ (f) (f)) (id-in f 1 4))