help-gnu-emacs
[Top][All Lists]
Advanced

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

Re: How the backquote and the comma really work?


From: tomas
Subject: Re: How the backquote and the comma really work?
Date: Fri, 26 Jun 2015 09:31:35 +0200
User-agent: Mutt/1.5.21 (2010-09-15)

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Thu, Jun 25, 2015 at 07:09:11PM +0200, Marcin Borkowski wrote:
> Hi all,
> 
> I decided that the time has come that I finally approach the scary
> backquote-comma duo.  (While I understand it superficially, I’d like to
> get it right and thoroughly this time.)  So my question is whether my
> mental model (see below) is correct.
> 
> So, I assume that when Emacs Lisp interpreter encounters a backquote, it
> looks at the expression after it.  If it is anything but a list, it just
> works like the usual quote, and the backquoted expression evaluates to
> what was backquoted.
> 
> If it is a list, its element are read and scanned.  If any part of the
> list (probably a nested one) begins with a comma, the whole thing after
> the comma (be it a symbol, a list or whatever) is evaluated as usual,
> and the result is put into the resulting list.

It's *always* read as an S-expression (i.e. either a symbol, a string,
a couple of more things, or a pair (thus, a list too). 

Thus something like `(bla bli would be an unfinished expression.

To put a slightly different slant than the other very good answers
on it, backquote is Lisp's take on the shell's, Perl's, Pythons "variable
interpolation". On those languages it operates on strings, in Lisp it
operates on S-expressions. Where in Perl you might say:

  my $amount=200;
  my $currency="dollars";
  print("You owe me $amount $currency\n");

  => You owe me 200 dollars

in Lisp you think in S-expressions. Somewhat equivalent would be

  (setq amount 200)
  (setq currency 'dollars) ; use a symbol, just for kicks
  (print `(You owe me ,amount ,currency))

  => (You owe me 200 dollars)

Of course, print shows the surrounding parentheses because the result
is a list in this case (an S-expression in general).

The whole magic of ` and , comes because you can "unquote" whole
sub-expressions: think

  `(you owe me ,(* amount 1.1) ,currency)

and because you can nest the whole thing (unquote within quote within
unquote ...).

It is just a minimalistic, but complete template language, in classical
Lisp tradition.

(and if you have a canonical transformation of e.g. S-expressions
to HTML, it's much more fun to write HTML templates in than the
usual template languages).

Now how this can be used to transform source code (i.e. "write macros")
is left as an exercise to the reader ;-)

Regards
- -- t
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEARECAAYFAlWM/9cACgkQBcgs9XrR2kYOFACeMkeLRxMLJHBrJ/n71ErVkZy1
QFIAmwcUEneXbHY+zcbmCDsTGRl97TM8
=AVmD
-----END PGP SIGNATURE-----



reply via email to

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