Search code examples
macrosschemer6rshygiene

Can someone explain the concept of 'hygiene' to me (I'm a scheme programmer)?


So... I'm new to scheme r6rs, and am learning macros. Can somebody explain to me what is meant by 'hygiene'?

Thanks in advance.


Solution

  • Hygiene is often used in the context of macros. A hygienic macro doesn't use variable names that can risk interfering with the code under expansion. Here is an example. Let's say we want to define the or special form with a macro. Intuitively,

    (or a b c ... d) would expand to something like (let ((tmp a)) (if tmp a (or b c ... d))). (I am omitting the empty (or) case for simplicity.)

    Now, if the name tmp was actually added in the code like in the above sketched expansion, it would be not hygienic, and bad because it might interfere with another variable with the same name. Say, we wanted to evaluate

    (let ((tmp 1)) (or #f tmp))
    

    Using our intuitive expansion, this would become

    (let ((tmp 1)) (let ((tmp #f)) (if tmp (or tmp)))
    

    The tmp from the macro shadows the outer-most tmp, and so the result is #f instead of 1.

    Now, if the macro was hygienic (and in Scheme, it's automatically the case when using syntax-rules), then instead of using the name tmp for the expansion, you would use a symbol that is guaranteed not to appear anywhere else in the code. You can use gensym in Common Lisp.

    Paul Graham's On Lisp has advanced material on macros.