[plt-scheme] macro help

From: Neil Van Dyke (neil at neilvandyke.org)
Date: Sun May 23 09:35:38 EDT 2010

Todd O'Bryan wrote at 05/23/2010 09:15 AM:
> I think I've crossed the border between syntax-rules and syntax-case,
>   

I'm not sure about the phases you mention, but regarding parsing the 
field list in "syntax-rules", an idiom I like to use it so have 'helper 
syntax' that goes through an input list argument and builds an output 
list in another argument.  You can try the following in the DrScheme 
Macro Stepper to see.


#lang scheme/base

(define-syntax define-my-struct
  (syntax-rules ()
    ((_ NAME (FIELD0 FIELD1 ...)) (%define-my-struct:1 NAME (FIELD0 
FIELD1 ...) ()))))

(define-syntax %define-my-struct:1
  ;; (_ NAME IN-FIELDS OUT-FIELDS)
  (syntax-rules ()

    ;; All input fields processed.
    ((_ NAME () (OUT-FIELD0 ...))
     (some-other-form
      :name NAME
      :fields OUT-FIELD0 ...))
   
    ;; Process a required input field.
    ((_ NAME
        ((FIELD-NAME FIELD-TYPE) IN-FIELD1 ...)
        (OUT-FIELD0 ...))
     (%define-my-struct:1 NAME
                          (IN-FIELD1 ...)
                          (OUT-FIELD0 ... (:required :name FIELD-NAME
                                                     :type FIELD-TYPE))))
                                     
 
    ;; Process an optional input field.
    ((_ NAME
        ((FIELD-NAME FIELD-TYPE FIELD-DEFAULT) IN-FIELD1 ...)
        (OUT-FIELD0 ...))
     (%define-my-struct:1 NAME
                          (IN-FIELD1 ...)
                          (OUT-FIELD0 ... (:optional :name    FIELD-NAME
                                                     :type    FIELD-TYPE
                                                     :default 
FIELD-DEFAULT))))))
                                     
(define-my-struct blah
  ([required1 symbol?]
   [required2 number?]
   [optional1 symbol? 'default]
   [optional2 boolean? #f]))

>
> P.S. Does anyone have a series of exercises that guide one through the
> complexities of macro writing?
>   
I learned from:
http://www.xs4all.nl/~hipster/lib/scheme/gauche/define-syntax-primer.txt


-- 
http://www.neilvandyke.org/


Posted on the users mailing list.