Question

I'm learning how the macro system in Scheme works and I'm trying to make my code look more JavaScript-y. So I thought I would start with the function macro. This is how I want a function definition to look:

(function id (x) x)

It should expand to the following:

(define (id x) x)

So I write a macro as follows:

(define-syntax function
    (lambda (name args . body)
        `(define (,name ,@args) ,@body)))

However when I use it I get the following error (in Chicken Scheme):

Error: during expansion of (define ...) - in `define' - lambda-list expected: (define ((function id (x) x) . #<procedure (rename sym1348)>) #<procedure (compare s11400 s21401)>)

    Call history:

    <syntax>      (function id (x) x)
    <eval>    (##sys#cons (##core#quote define) (##sys#cons (##sys#cons name args) body))
    <eval>    (##sys#cons (##sys#cons name args) body)
    <eval>    (##sys#cons name args)    <--

Where am I going wrong? In addition how do I read such error messages to be able to debug the program myself?

Was it helpful?

Solution

In Scheme, using syntax-rules():

(define-syntax function
  (syntax-rules ()
    ((function name (args ...) body ...)
     (define (name args ...) body ...))))

The error you are seeing is that apparently Chicken Scheme's compiler expects the second form of define-syntax to be a macro expansion procedure - they typically require arguments for renaming and comparing identifiers. The lambda in your macro doesn't produce a suitable function - syntax-rules does.

The above is guaranteed hygienic.

OTHER TIPS

The way you have defined the macro is not correct as per Chicken documentation. Your code seems to be more inspired by Common Lisp macros. Check out the doc here for define-syntax with transformer function:

The macro should be defined as:

(define-syntax function
    (lambda (expr inject compare)
        `(define (,(cadr expr) ,@(caddr expr)) ,(cadddr expr))))

expr is the whole macro expression i.e (function id (x) x) and inject and compare are special utility functions passed to the macro while perfoming macro expand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top