guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Naming conventions


From: Taylan Kammer
Subject: Re: Naming conventions
Date: Wed, 8 Jul 2020 21:16:11 +0200
User-agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:68.0) Gecko/20100101 Thunderbird/68.9.0

On 07.07.2020 13:05, Simen Endsjø wrote:
>
> - <symbol> :: ? As a macro parameter
>
I personally do this with pattern variables in macros, but I don't know
if anyone else does.  I'd advocate for it to become the norm though!

I find it very intuitive because pattern variables are placeholders for
something else, and the <blah> notation is often used for placeholders.
(This probably originates from BNF syntax.)

Consider the following example.

In Scheme it's customary to return #f (the false Boolean) to mean "null"
or "no result."  And it's a common pattern in code to try to get a value
from somewhere, then only do a certain thing if you got a result.

For that reason let's say I want to define an "in-case" macro, to be
used like this:

  (in-case warnings (check-warnings input)
    (display "Input is valid, but please note these warnings:\n")
    (for-each (lambda (w) (display w) (newline)) warnings))

I.e., the result of (check-warnings input) is bound to the 'warnings'
variable, and the code is executed if it's not #f.

I would define that macro like this:

  (define-syntax in-case
    (syntax-rules ()
      ((_ <variable> <expression> <body> <body*> ...)
       (let ((<variable> <expression>))
         (when <variable>
           <body> <body*> ...)))))

I personally find that significantly easier to read than this:

  (define-syntax in-case
    (syntax-rules ()
      ((_ variable expression body body* ...)
       (let ((variable expression))
         (when variable
           body body* ...)))))

In the latter variant, it's much less obvious that we have a piece of
"template" code with symbols or expressions to be inserted in certain
positions.

Especially the part with (let ((variable expression)) ...) is IMO much
clearer when using the <symbol> notation, because it makes it clear that
we're not binding a new variable literally called "variable" but rather
that, when the macro is expanded, it will bind a variable whose actual
name is provided by the user of the macro.

Maybe the difference isn't much in such a small example, but if the body
of the macro was bigger, it might help quite a bit.


I think the notation also has the benefit of making it more obvious for
newbies what exactly syntax-rules does and how it works.  In particular,
it might help to clarify that the second part of 'syntax-rules' is a
template, where snippets given by the macro user are inserted into
certain slots in the template.


- Taylan



reply via email to

[Prev in Thread] Current Thread [Next in Thread]