Scheme macro examples

I got stuck with macro explanation in Teach yoursef Scheme in fixnum days. Idea was pretty simple but implementation …. well I felt a bit lost like a gnome trying to get to AH in SW:

Then I dig out the define-syntax, experiment on my own and … here are some simple-like-pie examples:

Hello world are considered harmfull but one have to start somwhere:

#lang r6rs
(import (rnrs base(6))
        (rnrs io simple(6)))

(define-syntax do-magic
  (syntax-rules ()
    ((do-magic)
     (display "Huh? Why not just a procedure?"))))

(do-magic)
; uh? Why not just a procedure?

Example with macro witch invoke the procedure and passes parameter, for showing that usual way of interpreting list elements can be changed in macro:

#lang r6rs
(import (rnrs base(6))
        (rnrs io simple(6)))

(define-syntax apply1
  (syntax-rules ()
    ((_ proc-name proc-arg)
     (proc-name proc-arg))))

(apply1 display 7)
; 7

Now the same trick but with variable number of arguments

#lang r6rs
(import (rnrs base(6))
        (rnrs io simple(6)))

(define-syntax apply2
  (syntax-rules ()
    ((_ proc-name arg ...)
     (proc-name arg ...))))

(apply2 min 7 8 9)
; 7

More examples – this time with defining when. The simple way …

#lang r6rs
(import (rnrs base(6))
        (rnrs io simple(6)))

(define-syntax when1
  (syntax-rules ()
    ((_ test-expr expr-to-eval)
     (if test-expr expr-to-eval))))

(when1 (< 1 2) (display "it's a small steps for list programmer but enormous for my"))

… and proper way:

#lang r6rs
(import (rnrs base(6))
        (rnrs io simple(6)))

(define-syntax when2
  (syntax-rules ()
    ((_ test expr1 expr2 ...)
    (if test
        (begin expr1 expr2 ...)))))

(when2 #t (display 42) (newline) (display "it works"))
; 42
;
; it works

Cool 🙂

Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s