141 points · by gnosis · 15y ago · 80 comments
Huh? That's just blatantly wrong, and I (and many others) have used the C preprocessor to create multi-level macros in quite powerful ways. See for example http://blog.nelhage.com/2010/07/implementing-an-edsl-in-cpp/ or the insanity Linux's tracing macros have implemented: http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6...
His article has a point, but he's not doing C macros justice -- they are quite powerful and can be used in really cool ways, even if people tend to look at you funny when you do :)
Think about it.
> they are quite powerful
For small values of "quite". C macros are strictly less (and by large margin powerful than Lisp macros. One can't even use #ifdef inside #define!
The C macro system was already too powerful, and one of the things that hurts languages is a preprocessor of virtually any kind. The badness of the C preprocessor starts much earlier with things like include files, and the fact that you can't statically analyze the code in any reasonable way.
The benefit from the preprocessor is absurdly small. With that said, I think the benefit of the Lisp preprocessor is pretty small too. C would be harmed more by its omission due its compilation model, but as we've seen with languanges in its family, like C#, its unnecessary.
In a decade or less, the Lispers will see this light too.
The reason you can't statically analyze C code that uses macros has to do with the preprocessor's broken design - it is a separate stage from the compiler, and there's no way for the two to communicate.
All this actually means that Lisp macros can be used for static analysis (via macroexpand), in a user-extensible way, without needing to add extensions to the compiler or stages to the compilation process.
I don't understand why you cite C# as a good example of something that doesn't have code preprocessors. Visual Studio has T4 (Text Template Transformation Toolkit), which is a dumb joke.
Lisp doesn't have a preprocessor, Lisp is a preprocessor. You can program with it, but thinking about it as a programming language (ASCII or Unicode Strings to be Interpreted) is at least partially wrong.
"In a decade or less, the Lispers will see this light too."
It hasn't happened in the last half century, so how much do you want to bet on it?
In a decade or less, the Lispers will see this light too.
Right. It's just been invisible for the last 25 years. Or maybe the last 50. Whatever. One of these days...It's hard to quantify "general good" of something complex as programming language macro system with all consequences included.
But it's quite easy to see which one is more powerful wrt expressiveness.
Your primitive macro system _forces_ me to write code like this:
#ifdef CONFIG_AUDITSYSCALL #define INIT_IDS \ .loginuid = -1, \ .sessionid = -1, #else #define INIT_IDS #endif
#define INIT_TASK(tsk) \ { INIT_IDS }
instead of more natural.
#define INIT_TASK(tsk) \ {\ #ifdef CONFIG_AUDITSYSCALL .loginuid = -1, \ .sessionid = -1,\ #endif }
> The badness of the C preprocessor starts much earlier with things like include files, and the fact that you can't statically analyze the code in any reasonable way.
Static analysis hardness or easyness has _nothing_ to do with preprocessing, because static analyzer can preprocess code in a very same way compiler will so both will analyze the very same stream of tokens.
> The benefit from the preprocessor is absurdly small.
This is subjective and unquantifiable.
For example:
(defun sum (x y)
`(,x + ,y = ,(+ x y)))
This is a SUM function which looks like this when run: (sum 4 5) ==> (4 + 5 = 9)
The backquote (`) says the following form and its sub-forms (if any) are all quoted. But you can poke holes in the quote and fill in with the value of outside variables, using comma (,). So in the example, everything is quoted in the body of sum, except three things: x, y, and (+ x y). Each of those is then evaluated yielding 4, 5 and 9, then, finally, the template is filled in (4 + 5 = 9).If you want to confirm this, you can change the + and = to any other symbol and it would still display. E.g:
(defun sum (x y)
`(,x frob ,y != ,(+ x y)))
(sum 4 5) ==> (4 FROB 5 != 9)I think combining backquote-comma's s-exp-making and s-exp-destructuring powers is a viable way to abstract s-exps from their representations as linked lists/arrays/whatever sequence you want to use.
http://www.lisperati.com/looking.html
"Flip, flop, flip, flop..."
(mac until (test . body)
`(while (no ,test) ,@body))
It's really useful for bodies of code like this.The same can be said for classic Forth. Indeed, the enthusiastic way that Lispers describe macros I find eerily similar to how I used to hear Forthians describe their language. Except in Forth the relevant term isn't macro but "defining word". Indeed, I think programmers in both camps see the proper use of macros/defining words as a sign that one has passed the beginner stage of using the language.
A classic compiled Forth word (ie, function) would consist of the word's name followed a string of addresses to execute; how those addresses were laid down, where they pointed, etc. were totally open to programmer control -- both during compilation and afterwards. It's been a couple of decades since I looked at Forth code, but I don't think there's anything that could be done in Lisp macros that couldn't also be done easily in Forth as well.
I think the big difference between the two -- at least, so far as the macro topic goes -- is that Lisp starts with an assumption that code and data can and should be interchangeable while Forth was initially developed for the machine control (embedded systems before they were called embedded systems) and thus code was merely a vehicle for creating applications.
Forth is an interpreter that can be switched into compilation mode, Lisp is a compiler that can be switched into interpreter mode. [edit: thinking of that, this more reflects how I have used the two than what they are. Lisps start in an eval loop, too, yet they feel different to me]
Forth is postfix, Lisp is prefix.
Forth programmers know their stacks are the environment, but rarely think of it as an environment. Lisp programmers know their environment is in some stack-like data structures, but rarely think of those stacks.
1. Macros aren't unique to lisp. They're most developed and used in the lisp family, but you don't need to have a homoiconic language to have macros. The Mirah programming language--statically typed Ruby on the JVM--has non-hygenic macros, I know there's been a number of efforts to add macros to coffeescript (so far without success), and there are a number of academic languages that also have them. None are in widespread use, but they exist.
2. Metaprogramming's power is primarily limited by the restrictions of the host language. The best example I know of is Io where pretty much anything other than commas and parentheses is up for grabs. Example: http://anttih.com/blog/2010/10/29/json-in-io.html
3. User definable mixfix operators are in the sameish domain. Unfortunately, they're almost always mentioned in passing by people who know what they are so I don't have a good reference for introducing what they are and don't have direct experience working with them. I'm just mentioning them as something to be aware of if you're interested in general metaprogramming concepts. Here's the closest thing to an intro I could google up: http://maude.cs.uiuc.edu/maude1/manual/maude-manual-html/mau...
Perl6 also has macros (http://en.wikipedia.org/wiki/Perl_6#Macros) though they haven't been implemented in Rakudo yet. Also Ioke states that it has macros.
2. Metaprogramming's power ... The best example I know of is Io where pretty much anything other than commas and parentheses...
Touched on Io introspection/metaprogramming before on HN:
ref:
* http://en.wikipedia.org/wiki/Perl_6_rules
2. Io is great but the depth of it's runtime meta-programming facilities make it horrifically inefficient.
As for Io's efficiency, I think that's more about the implementation than in the language. Javascript (prototypal inheritance) and Smalltalk (message passing) aren't that far off and both have decent performance. I know Steve Dekorte was working on getting Io running in javascript in December but I don't think it's a high priority project for him.
For (3) look at how Haskell defines new operators. I find Haskell's use of completely new operator-squiggles plus type classes for something faintly similar to C++-style overloading, much more sensible than say, C++-style overloading.
> Except, of course, that doesn’t work. The preprocessor
> only makes one pass through the file, meaning a macro
> can’t call another macro.
macro.c:
#include <stdio.h>
#define LOOP(n) for (int i = 0; i < n; i++)
#define PRINT10 LOOP(10) { printf("%d", i); }
int main(void) { PRINT10; printf("\n"); }
gcc -Wall -std=gnu99 macro.c && a.out
0123456789
Of course macros can call other macros:
http://gcc.gnu.org/onlinedocs/cppinternals/Macro-Expansion.h...Ignoring his poorly protected macros, and taking nothing away from Lisp, am I missing some subtle point he's making, or is the author just flat out wrong here? I think he's just wrong, and this makes it hard for me to even read the rest of his argument.
(a nonsensical example, as I can't think of a proper one right now)
#define PRINTFOO PRINTBAR
#define PRINTBAR PRINTFOO
PRINTFOO
The ANSI C standard says a macro, while it is being expanded by the preprocessor, ``is painted blue'' (is no subject to further expansion).
I'm not sure, but probably it follows the C macros are not Turing-complete.
EDIT: on the other hand, a LISP macro system is a Turing-complete programming language that's geared towards manipulating lists of symbols and values (which, incidentally, is LISP program).
Perhaps I was wrong; perhaps the phrase was in K&R C? Can't find the book online @_@;;
#include <stdio.h>
#define LOOP(n) \ int i; \ for (i = 0; i < n; i++)
#define LOOP10 \ LOOP(10) printf("%d\n", i)
int main(int argc, char *argv[]) { LOOP10; }
Here it is:
(defmacro for-duration ((seconds) &body body)
`(handler-case
(bt:with-timeout (,seconds)
,@body)
(bt:timeout () nil)))
Five lines to alter the evaluation model of your language. Not bad.Use as:
(for-duration (10)
(loop
(print "Infinite loop! where is your Godel now?")))
"bt" is the bordeaux-threads package, a portable Lisp library for thread programming. (defun for-duration (seconds body)
(handler-case
(bt:with-timeout seconds
(body))
(bt:timeout () nil)))
(for-duration 10
(lambda ()
(loop
(print "Infinite loop! where is your Godel now?")))) #define for_duration(seconds, body) \
{ \
pthread_t tid_task, tid_watcher; \
\
void* task(void* arg) { \
body ; \
pthread_cancel(tid_watcher); \
return NULL; \
} \
\
void* watcher(void* arg) { \
sleep((seconds)); \
pthread_cancel(tid_task); \
return NULL; \
} \
\
pthread_create(&tid_task, NULL, &task, NULL); \
pthread_create(&tid_watcher, NULL, &watcher, NULL); \
pthread_join(tid_task, NULL); \
}
Use as: for_duration(10, {
while (true) {
printf("Infinite loop! where is your Godel now?\n");
}
});
Or with single brace-less statements: for_duration(10, while (true) printf("something\n") );
Lexical scope is sane: int i = 0;
for_duration(10, {
while (true) {
printf("%d\n", i++);
}
});
My comparison isn't quite fair, because your threading library provides 'with-timeout', while pthreads doesn't. If you factored this out, say with a signature like: void with_timeout(unsigned int seconds, void (*func)(void));
(in analogy to the common lisp function), then the macro part becomes just four lines: #define for_duration(seconds, body) { \
void func() { body ; } \
with_timeout((seconds), &func); \
}
I acknowledge that the lisp solution is rather more elegant. Also, my C macro is potentially dangerous because it is unhygenic. (It shadows outer declarations of 'task()', 'watcher()', 'tid_task', 'tid_watcher', and 'arg', in the body of 'body'.) (defmacro execute-in-reverse (&body body)
`(progn ,@(reverse body)))
(execute-in-reverse (print "Hi") (print "Middle") (print "Bye"))
Prints... "Bye"
"Middle"
"Hi"
Point: You can do whatever you want with the symbols sent to the macro, whatever their contents. Mahmud's wrapper macro is trivial (it could be done with lambdas). Lisp's macro system allows you to create new syntax, including changes in flow control.But my example is trivial, too. I could go on to swap individual parts of my forms around, remap them to other forms depending on various conditions, etc.
In addition, people often talk about Lisp macros, but they neglect to mention the power of reader macros, which allow you to go beyond Lisp's basic AST look-and-feel.
If you've ever built a string in T-SQL or PL/SQL and then exec'd it, you're probably much closer to being productive with macros than you think.
Of course, this is probably because dynamically generating SQL is something that I've done. Other programmers probably have their own mental models that warp into lisp.
Now there's an idea...
I can see why they are as powerful as claimed.
(loop for y = 0 then z
for x from 1 to 5
sum 1 into z
finally (return (values y z)))
and then evaluate this: (loop for x from 1 to 5
for y = 0 then z
sum 1 into z
finally (return (values y z)))I agree with the definition at http://en.wikipedia.org/wiki/Metaprogramming
A key tradeoff is that they must be expanded at run-time, and in doing so they incur a performance penalty that doesn't exist with compile-time macros.
However, we have no useful English operators to take the quoted words and change them into something else meaningfully. Though a non-English set can be argued to exist: http://creativeservices.iu.edu/resources/guide/marks.shtml If those were English themselves that would arguably complete the loop, but I would consider that stretching the point; these were explicitly invented to avoid the use of English and also translate to any other character-based language.
X-bar theory says that in all natural languages, Noun Phrases, Verb Phrases, and depending on who you read other types of phrases all have the same form; a single Head (which may be composite) and a Tail with zero or more elements. Never mind that they've just discovered S-expressions. The point is that in the natural language program:
multiply the radius squared and pi
Both the data-like parts and the program-like parts share the same structure.But seriously, take a look at Quines and Hofstadter's Godel, Escher, Bach
(let ((let '`(let ((let ',let))
,let)))
`(let ((let ',let))
,let))
Originally from: http://www.scribd.com/doc/47702904/Bawden-Quasi-Quotation-in...i wish authors didnt craft their arguments around C/Java.