A common Scheme idiom is to return
#f in the case of failure and
a useful value otherwise. For example, the
member function returns
false when an element cannot be found, and the sublist from the first
match on success. As we may want to use the result of the call we
must bind it to a name and then test it. The example below shows this.
(let ((result (member 3 '(0 1 2 3 4))))
(if result
'found
'not-found))
It would be nice to abstract this idiom.
The
aif macro captures this common idiom. Using the
aif macro,
we can write the above example as:
(require (lib "aif.ss" "macro"))
(aif result (member 3 '(0 1 2 3 4))
'found
'not-found)
The name
result is bound to the result of
(member 3 '(0 1 2 3 4)).
The value of
result is then used in a normal
if expression to
choose between the true and false arms.
A slightly more complicated case occurs when the result of the
expression must be compared using a predicate before we can decide
which arm to take. This occurs, for example, when reading from a
file.
(define (port->string-list port)
(let ((line (read-line port)))
(if (eof-object? line)
(list)
(cons line (port->string-list port)))))
The
aif macro handles this case as well.
(require (lib "aif.ss" "macro"))
(define (port->string-list port)
(aif line eof-object? (read-line port)
(list)
(cons line (port->string-list port))))
The definition of
aif is
(define-syntax aif
(syntax-rules ()
((_ name test true-arm false-arm)
(let ((name test))
(if name
true-arm
false-arm)))
((_ name pred test true-arm false-arm)
(let ((name test))
(if (pred name)
true-arm
false-arm)))
))
The
aif macro is adapted from Paul Graham's "
On Lisp".
It is short for
anaphoric if.
I find this a great example and motivation for syntax-rules macros.
Whether it qualifies as an idiom I am not sure about - I don't
think I have seen
aif in the wild except in Noel's code ;-)
--
JensAxelSoegaard - 19 May 2004
Yeah, and even I don't use it that much as I haven't got around to releasing the Schematics macro library! Anyway, I added the macro definition to maybe others will use it.
--
NoelWelsh - 19 May 2004
--
NoelWelsh - 19 May 2004