Search code examples
common-lispmit-scheme

How to write a simple macro in MIT Scheme?


I am trying to translate this simple Common Lisp macro code to MIT Scheme code:

(defmacro calc (a op b)
  (list op a b))

(calc 2 + 3)

The above code prints 5 as expected.

How do I do the same thing in MIT scheme? Here is my attempt:

(defmacro (calc a op b)
  (list op a b))

(calc 2 + 3)

The above code fails with this error:

Unbound variable: b

What is the right way to write this code in MIT Scheme?


Solution

  • While many Scheme implementations has defmacro it differs if it has arguments like in Common Lisp, Scheme or if the expression is also a special form. It is not portable. From R5RS you can use `syntax-rules:

    (define-syntax calc
      (syntax-rules () 
       ((_ a op b)   ; pattern  
        (op a b))))  ; expansion
    
    (calc 4 + 3) ; ==> 7