doc.txt

Macro Library

_Macro_ Library
===============

By Noel Welsh (noelwelsh at yahoo dot com)
and Dave Herman

Time-stamp: <2008-03-11 14:27:55 noel>

Keywords: _macro_, _aif_, _abegin0_, _for_, _iteration_


Introduction
============

This library provides some useful macros.  Please
contribute additional macros to the library.

To use the whole library:

   (require (planet "macro.ss" ("schematics" "macro.plt" 1 2)))


_Anaphoric If_
==============

To use just these definitions:

   (require (planet "aif.ss" ("schematics" "macro.plt" 1 2)))

> (aif name [pred] expr true-arm false-arm)

The result of expr is bound to name in the scope of true-arm
and false-arm.  If (pred result) is not #f true-arm is
evaluated; otherwise false-arm is evaluated.  By default
the identity function is used for pred.

The _aif_ macro captures a common 3-step pattern:

  1. Evaluate an expression yielding a result v

  2. Test v for some condition

  3. Perform different actions on v depending on the result
     of the test.

Crucially the value v is used in the actions, so a simple if
statement will not suffice.  A common case occurs when
reading data from a port and checking for the end-of-file
condition.  For example

   (let ((result (read-line port)))
     (if (eof-object? result)
         (display "End reached")
         (display result)))

can be written using aif as:

   (aif result eof-object? (read-line port)
        (display "End reached")
        (display result)

This macro is based on one given in 'On Lisp' by Paul
Graham.


_Anaphoric Begin_
=================

To use just these definitions:

   (require (planet "abegin.ss" ("schematics" "macro.plt" 1 2)))

> (abegin0 name expr expr1 expr2 ...)

The result of expr is bound to name in the scope of the
following expressions.  The result of the entire abegin0
expression is the value bound to name.

The _abegin0_ macro captures a common pattern:

  1. Evaluate an expression yielding a result name

  2. Perform some side-effecting operations with name, such
  as logging it's value.

  3. Return the value of name.

Example:

  (let ((result (calculate-something)))
    (log result)
    result)

can be written as

  (abegin0 result (calculate-something) (log result))