[plt-scheme] Applying DRY in macros

From: Jens Axel Soegaard (jensaxel at soegaard.net)
Date: Sat Sep 13 07:32:59 EDT 2008

Anthony Cowley skrev:
> Does that one do the right thing? I thought it would have been phrased 
> more like...
>
> (define-syntax (for3 stx)
>   (syntax-case stx ()
>     ((for x in/as y body ...)
>      (let-values (((element list) (cond 
>                                     ((free-identifier=? #'in/as #'in)
>                                      (values #'x #'y))
>                                     ((free-identifier=? #'in/as #'as)
>                                      (values #'y #'x))
>                                     (else (error 'for "Invalid 
> syntax")))))
>        #`(map (lambda (#,element) body ...) #,list)))))
>
Nope, I missed that the fact that the order was reversed.

Here is an alternative:

(define-syntax (for stx)
  (define (template var list-expr bodies)
    #`(map (lambda (#,var) #, at bodies) #,list-expr))
  (syntax-case stx (in as)
    [(for element in list body ...)
     (template #'element #'list #'(body ...))]
    [(for list as element body ...)
     (template #'element #'list #'(body ...))]))

-- 
Jens Axel Søgaard



Posted on the users mailing list.