by WalterGR · 11y ago · 0 comments
I didn't "get" macros until I read a footnote in the (freely available) book Practical Common Lisp. In chapter 7, it introduces the `dolist` macro.
DOLIST loops across the items of a list, executing the loop
body with a variable holding the successive items of the list.
This is the basic skeleton (leaving out some of the more
esoteric options):
(dolist (var list-form)
body-form*)
...For instance:
CL-USER> (dolist (x '(1 2 3))
(print x))
1
2
3
NIL
Buried in a footnote is this:"DOLIST is similar to Perl's `foreach` or Python's `for`. Java added a similar kind of loop construct with the 'enhanced' for loop in Java 1.5, as part of JSR-201.
Notice what a difference macros make. A Lisp programmer who notices a common pattern in their code can write a macro to give themselves a source-level abstraction of that pattern. A Java programmer who notices the same pattern has to convince Sun that this particular abstraction is worth adding to the language. Then Sun has to publish a JSR and convene an industry-wide "expert group" to hash everything out. That process--according to Sun--takes an average of 18 months. After that, the compiler writers all have to go upgrade their compilers to support the new feature. And even once the Java programmer's favorite compiler supports the new version of Java, they probably still can't use the new feature until they're allowed to break source compatibility with older versions of Java.
So an annoyance that Common Lisp programmers can resolve for themselves within five minutes plagues Java programmers for years."
http://www.gigamonkeys.com/book/macros-standard-control-cons...
Can, say, a Lisp macro be 'partially formed', in the sense that it can expand into some boilerplate that represents an incomplete syntax tree? (Whereas a higher-order-function is necessarily complete.) I can see that being useful, but not inasmuch a it's made out.
if (log.isDebugEnabled()) {
log.debug("expensive" + debug + message);
}
This is "better" than just log.debug(...) because with the latter, your expensive log message argument needs to be evaluated even if debug is disabled.However, in a language w/ macros, you just say:
(debug (str "expensive" debug message))
and these considerations are already taken care of for you:https://github.com/clojure/tools.logging/blob/master/src/mai...
I don't understand why this is special?
Why can't you rewrite log.debug to include the check?
func debug(m string) {
if log.isDebugEnabled() {
log.debug(m);
}
}
What makes macros special in this case?Of course, with support for first-class functions, you could do something like:
func debug(produceMessage ()->string) {
if log.isDebugEnabled() {
log.debug(produceMessage());
}
}log.debug("expensive %s %s", debug, message)
The message is not actually formatted into one string unless the DEBUG trace level is enabled. Of course, you are still passing the arguments around, but with object references that's a negligable difference.
I still appreciate the solid example of a problem macros are good at solving, though. Two ways around one problem.
log.debug(debugIsEnabled and "yo expensive" or "yikes!")?
(change syntax to actually work)
Say Clojure forgot to ship with the boolean "or". "or" should evaluate its arguments one at a time (to allow for short circuiting) and return the first non-false value. You could do this with functions, but you have the source-level overhead of manually wrapping everything, and performance overhead of defining and passing an anonymous function for each argument. With a macro, at compile time you just translate the "or" macro into a simpler form that uses "if". This is how Clojure actually implements "or":
(defmacro or
"Evaluates exprs one at a time, from left to right. If a form
returns a logical true value, or returns that value and doesn't
evaluate any of the other expressions, otherwise it returns the
value of the last expression. (or) returns nil."
{:added "1.0"}
([] nil)
([x] x)
([x & next]
`(let [or# ~x]
(if or# or# (or ~@next)))))I find it a very elegant way of having everything clean, "lambda" does not even have to be a primitive anymore.
Consider a classic pattern of a with macro:
(with-mutex-held-macro (some-mutex) (do-stuff))
(call-with-mutex-held-hof some-mutex (lambda () (do-stuff))
A minor advantage is that a macro will be expanded in-line; a Sufficiently Smart Compiler could transform the HOF version into something equivalent, so it's not strictly an advantage (except to compiler implementers I suppose).I think that e.g. generalized references (i.e. the common lisp setf macro) are not possible with HOF, but HOF is more common in pure languages where assignment is eschewed anyway.
Mark Jason Dominus (author of Higher Order Perl) had some good comments on lisp macros as well:
http://lists.warhead.org.uk/pipermail/iwe/2005-July/000130.h...
function SpecDeclP()Parser{
return Bind(SeqRight(MyKeywordP, IdentifierP), function(nm interface{})Parser{
return Bind(BetweenParensP(IdentifierP), function(parm interface{})Parser{
return Bind(SetSwitchUserStateP, function(_ interface{})Parser{
return Bind(BlockP, function(bod interface{})Parser{
return Result("func " + nm.(string) + "(" + parm.(string) + ")" + bod.(string))
})
})
})
})
}
...with this more readable version if I have a recursively defined "macro" called doparse... doparse{
nm <- SeqRight(MyKeywordP, IdentifierP)
parm <- BetweenParensP(IdentifierP)
SetSwitchUserStateP
bod <- BlockP
Result("func " + nm.(string) + "(" + parm.(string) + ")" + bod.(string))
}
This requirement arose in Haskell for its Parsec before it became a part of the syntax, then again later with the Arrow library which later also added it to the syntax. Whenever new abstractions are discovered/created, a macroing facility, whether for lisp-like syntax or some other, helps makes all the nested functions more readable. with-open-file(filename, lambda file: do stuff with file)
but with a lisp macro, you only have to write with-open-file (filename):
do stuff with file
The point of an abstraction is so you don't have to think about the implementation. Written like the latter, with-open-file is simply more natural to write this way. You only have to think, "oh, its a construct that opens a file then closes it after the body is done", rather than "oh, its a higher order function that i have to pass another function into that takes the file as an argument..." etc.When you write with-open-file as a macro, it could be implemented as a higher order function, or it could be implemented as a low level set of GOTO statements. It doesn't matter. The macro abstracts away the low level detail, just providing the most natural way for you to use the construct. It might not seem like the macro is doing much in that particular example, but a construct that defines a class (like defclass) is something you can write as a macro, which can expand into functions that do the actual defining. You could write a class defining construct as a higher order function, but then you'd have to constantly worry about how your construct was implemented as a function. instead of just writing something natural like
defclass tiger (animal):
age init-value: 0
name type: string
which you could write if you implemented defclass as a macro.
otherwise,
you'd have to do something crazy stupid like defclass(name='tiger', inherits-from = find-class('animal')
slots=['age, name'] ...)
how could a higher order function possibly implement that without making people using it tear their hair out?
They have to bend to the implementation, not make the abstraction bend to what's natural. with_open_file filename do |f|
do stuff with file
end
And for your second example: # our 'macro' function
def defclass(name, parent, &blk)
k = Class.new(parent)
k.instance_eval(&blk)
Kernel.const_set(name, k)
end
defclass :Tiger, Animal do
attr_accessor :age, :name
end
Yes, macros allow for a superset of what you can reasonably accomplish with higher order functions, but I haven't yet seen a simple practical example of where the added power is useful. I'm sure it's nice to have, but there's something to be said about a language which generally gets you 95% of the way there using a simple set of built-in operations.If you haven't seen a practical example of what it's useful for, that's akin to the attitude of a C programmer not understanding the usefulness of higher order functions. They say, I get 95 percent of the way their with good old functions and function pointers. We would find that absurd, just as how I find the claim that a 'simple practical example of where added power of a macro is useful does not exist' is absurd
For example, see 'A unit testing framework' in 'practical common lisp' available online by Peter seibel. I can't possibly imagine how you'd be able to create a unit testing framework abstraction in Ruby as nice or efficient as the one presented with higher order functions in 26 lines of code. But it'd be cool if anyone could prove otherwise.
But since macros operate at the syntax level, they can do things functions can't do. For example, they can generate and manipulate declarations. Say you're working with abstract syntax trees (assembly trees in a CAD app might be another example). These trees are built from nodes, where each node is of some class corresponding to a syntactic construct: if-statement, addition-expression, etc. etc. There's some functionality you want to have on every node class; a common example is a "children" method that gathers up all the node's child slots into a set and returns it. It is very convenient to have a 'define-node-class' macro that automatically generates the 'children' method, so that when you add a child slot, the method is updated automatically; there's no need for manual effort to keep them in sync.
In this case, the macro is expanding to multiple top-level declarations: the class declaration along with the method declaration (probably, in practice, several methods). Higher-order functions don't begin to let you do stuff like this.
class Node {...}
class Expression extends Node {...}
class Addition extends Expression {
Expression left, Expression right;
Set<Node> children() {
return [a set containing 'left' and 'right'];
}
}
There's no way to write a single method 'children' on Node that will work for all its subclasses, because the method on Node can't access the subclasses' slots -- unless you use reflection, which is ugly and slow.Each answer exposes one or more facets of macros. Indeed, there is not just 'one' thing that make them worthwhile.
A part of the answer is: you probably don't need the kinds of macros which cover up machine-generated lambdas, which simulate non-strict evaluation in strictly evaluated Lisp programs! The compiler for your language already has these "macros" in its compiler.
The argument why "you always need macros no matter what else you have" is that your language has "hard-coded macros": the grammar rules in a compiler, which match patterns and transform bits and pieces to produce AST fragments. If you don't have macros, then that set of "hard-coded macros" is all you have.
So, even in a functional language with nonstrict evaluation, you're using macros. It's hard to make a convincing argument that they provide all the expressivity you would conceivably ever need. (And their existence and use defeats any argument that you don't need macros at all).
Which definition of "macro" are you using, if you equate lazy evaluation with a kind of "hardcoded macro"?
More importantly, "it's hard to make a convincing argument that [these hardcoded macros] provide all the expressivity you would conceivably ever need" doesn't convince me. A better argument would be to produce a compelling example where these "macros" are not enough. And by compelling, I mean something that cannot be elegantly produced in a non-Lisp language.
Yet, with macros I have this:
./txr -p '(mlet ((x (lcons 1 x))) x)'
(1 1 1 1 1 1 1 1 1 ... nonterminating sequence of 1's ...
This created a circular list!The special mlet ("magic let" or "mutual let") construct has allowed the expression which initializes s, (lcons 1 x), to refer to x.
This works because both mlet and lcons are macros. The lcons macro (rather, the code generated by the macro!) returns a lazy cons cell, without immediately evaluating its arguments 1 and x. In the case of x, this is a damn good thing because x is not yet initialized! When the lazy cons is accessed (when the list object is printed), the evaluation of x takes place. By that time, x holds the lazy cons cell, and since the variable x is in scope of the argument x in (lcons 1 x), the lazy cons is able to force, setting its CDR field back to itself, creating not a lazy list, but a circular list.
With lcons, I we can make a fibonacci function quite similarly to how you might do it in Haskell:
(defun fib2 (a b)
(lcons a (fib2 b (+ a b))))
We call this as (fib 1 1) and it gives us a lazy list.Here, we have a marriage between a lazy data structure and a macro. Without lazy conses, the lcons macro would have no target language to expand into. Without the lcons macro, lazy conses can't be used in the above convenient way; we would have to write fib2 in terms of the macro expansion:
$ ./txr -p "(sys:expand '(defun fib2 (a b)
(lcons a (fib2 b (+ a b)))))"
(defun fib2 (a b) (make-lazy-cons (lambda (#:lcons-0001)
(rplaca #:lcons-0001 a) (rplacd #:lcons-0001 (fib2 b (+ a b))))))The circular list mlet, when fully expanded looks like this, by the way:
$ ./txr -p "(sys:expand '(mlet ((x (lcons 1 x))) x))"
(let (#:g0001) (sys:setq #:g0001 (cons 'sys:promise
(cons (lambda () (make-lazy-cons (lambda (#:lcons-0046)
(rplaca #:lcons-0046 1)
(rplacd #:lcons-0046 (force #:g0001))))) '(delay (lcons 1 x))))) (force #:g0001))
It's a gritty oat-meal of delays, lambdas, forces, and cons manipulation. One thing that is conspicuously absent amid the toenail clippings: what happened to the x variable? Haha!Macros allow for the arbitrary evaulation of it's arguments (rather than the standard left to right order before a function call), allowing you to do syntactic extensions without the added boilerplate that functional languages can require.
Essentially, each macro allows you to define a mini-language that is parsed by the compiler that returns code that is then compiled. It takes a while to groc, but once you do you can never really go back.
A LISP macro is a syntax transformation. It lets you write code in the way you want to, instead of whatever level of abstraction you used to have.
I'm not sure about 'partially formed' code output, but 'partially formed' input is definitely possible. The way to invoke a LISP macro need not be valid LISP. In short, LISP macros excel at creating domain-specific languages.
# Define procedures named int? float? etc that test the type of a value.
(def def-type-predicate (mac (type-name)
`(def ,(string-to-symbol (join "" $type-name "?"))
(proc (x) (eq? (type x) ',type-name)))))
(def-type-predicate int)
(def-type-predicate float)
(def-type-predicate bool)
(def-type-predicate string)
(def-type-predicate symbol)
(def-type-predicate file)
(def-type-predicate nil)
(def-type-predicate pair)
(def-type-predicate procedure)
(def-type-predicate macro)
(zap def-type-predicate)
The crucial thing about what happens there being that the (def foo? ...) value produced by each macro invocation then gets evaluated in the root/top-level environment and so results in a "global" procedure definition. Using them: (string? (add 2 2))
=> FALSE
(float? 4.7)
=> TRUE
(procedure? string?)
=> TRUE
I thought it was a nice contained example of "code writing code" in the data realm.and istype(5, int) doesn't seem that much different than (int? 5)
I bet there's a version in c++ with templates and typeid.
This can provide an important speed improvement for complex macros or code used often, in tight loops or frequently called functions (it's like using inline methods in .h files in C++).
The advantage of CL macros is you can use functions written for your program to use at run-time during compilation-time/macro evaluation too.
Macros can fundamentally change code. Codewalkers. Back when OOP was a big thing (probably still is), Lisp programmers would probably amuse themselves by making object-oriented extensions to the language via macros, and sending them to each other.
This means that you are empowered, not just a language implementer. (First-class functions are important, and typically a better idea than "Guess I'll write my own macro!" but they only go so far.)
In case of using high-order procedure all its arguments will be evaluated in order before application of the procedure while in case if a macro you could explicitly define all the transformations (evaluation rules) for each argument. This is why it is called a special form - it has its own evalustion rules.
Shortcircuiting if or and are canonical examples.
So, with macros you are extending Lisp with new special forms.
Lisp supports first-class, high order functions. In fact, it was probably the first language to do so.
Macros are different. And they're not just "expanded." Think of macros as full blown Lisp functions that run at compile time and generate new Lisp code, that is itself compiled at compile time. Since Lisp code is represented as Lisp's list data structure, it's super easy. The macro system does allow expansion/replacement (like C's preprocessor), but that's just scratching the surface.
Is this similar to needing a dozen nearly-identical lines of code, writing one, then using Excel to manipulate the other 11 lines into what you want, then copying it back (and cleaning tabs in the process)?
Essentially programmatically writing the program - is that what Lisp's macros are?
Essentially programmatically writing the program -
is that what Lisp's macros are?
Macros are often described that way. "Lisp macros let you write code that writes code!" While that's a true statement, it's kind of useless for coming to an initial understanding of what macros let you really do.Think of it this way. Programming languages have built-in control flow operators like if-then, do, while, and for. Macros let you write your own operators - that work just like the ones built into the language itself.
Here's an example. Let's say you want to print a list of names.
In a language without an operator specifically for going over lists - and without macros - you may have to write:
ListIterator iterator = namesList.GetListIterator();
while(iterator.HasMoreItems()) {
string name = iterator.GetNextItem();
print(name);
}
If you have a language that supports macros, you can create a macro called forEachItemInList. And then it'll work just like it came with the language all along: forEachItemInList(string currentName in namesList)
{
print(currentName);
}
If you count how many words the non-macro solution took, it's 13. The macro solution takes 7. Having to solve a problem with more code means more time to understand, teach, write, test, debug, and document - so savings like this can really add up.And there's also the subjective part. Having to write code like in the first example just isn't satisfying. You have to repeat yourself constantly. You may think, "Look, I loop over lists all the time. And it's always the same pattern: I call GetListIterator(), I do a 'while' loop while it HasMoreItems(), then I call GetNextItem(), etc. Why can't I just inform the compiler of the general pattern - and then tell it how to fill in the blanks when I need to actually loop over a list?"
And that's what macros let you do.
The fundamental unit of Lisp is expressions of the form (FOO ...). There are three basic cases.
1. FOO is one of a finite list of special forms. Those are the irreducible base of that language.
2. FOO is a function. In which case the ... is evaluated as Lisp (possibly including doing things like expand out other functions) before being passed to that function.
3. FOO is a macro. In which case the ... bit is turned into a list of things, but NOT evaluated, passed to the macro to be rewritten, and then the result is turned into an expression that is then evaluated by the same rule.
This is not completely true. There is a preprocessing step called reader macros that can do things like turn `(this expression) into (QUOTE this expression) to save typing. But those are very sparingly used.
https://github.com/slburson/misc-extensions
Look in src/gmap.lisp.I admit it wouldn't work that well for 'n-at-a-time', but here's a closely related example:
(defun alist-to-plist (alist)
(gmap :plist nil (:alist alist)))
There are some idiosyncrasies here: 'nil' is shorthand for the identity function (in this case, the two-argument, two-value identity function), and the use of keyword symbols is weird and potentially problematic, though I've never run into a problem with it in practice.This is the map-reduce model of iteration -- obviously not with support for distributed computation, but nonetheless useful for programming in the small. And far more elegant, to my eyes, than that LOOP monstrosity :-)
I haven't bought into this "Lisp macros are the best thing since sliced bread" idea, but without a doubt they are infinitely more awesome than C macros.
I get the sentiment, but this is seriously advocating for unmaintainable code that likely breaks in strange corner cases and requires 10 times as long for a new person to the code base to understand.
First contributor, "I know my code should be able to handle out of memory errors in this corner case, but I know I won't use it that way so it shouldn't be an issue."
Second contributor, "Hey this macro from First contributor looks nice, I'm going to use it."
A pile of shit emerges.
Lisp aims itself into niche problems where there's nothing good enough done yet. For the rest people won't care about the ability to fit the language to their need, they want 'productivity' and if a pattern become useful, backpressure will force language designer / BDFL to change it.
However, if we broaden the concept a little, we can do this type of macros for any language with a meta-layer such as MyDef. e.g. if you observe certain foreach pattern in Java, you can make a macro for that pattern and have the meta-layer look out and translate that for you (like having an automatic translator between you and javac. All you need is a scope type macro. Conventional macro packages like M4 does not provide such, but MyDef does. Example:
&call each_member, AList
# java code that work on $(member)
where the macro may be defined as subcode: each_member(list)
Enumeration e = $(list).elements();
while (e.hasMoreElements()){
String name = (String) e.nextElement();
$(set:member=name)
BLOCK
}
Where it is understood that the definition can be any literal block pattern. Macros are what made lisp, not parentheses.
The parentheses are huge, though. It enables "Code is data" and "Data is code" in a powerful way.About Lisp, people always say "Macros are great" and "Code is data" and "Data is code", but it's hard to see what they mean without good examples. I mean, you can write code that writes code in any language that has a `print` statement. And obviously code is data, so what is that aside from some pseudo-philosophic BS?
There's a lot of discussion in this thread about macros - so here's an example of Code and Data Being One, for those that are unconvinced. I hope it'll shed some light.
I have a slang dictionary website. It's backed by a database now, but it used to be statically-generated HTML. I represented the data as XML. It looked something like this:
<Term term="slick">
<PartOfSpeech pos="adj">
<Definition>
impressive.
</Definition>
<Definition>
smart.
</Definition>
</PartOfSpeech>
</Term>
So then I needed an XML parser to parse the data. Maybe it parsed the XML into a object model that the code would navigate and output the appropriate HTML. Or maybe the code got callbacks according to node type and would output the appropriate HTML then.XML is a pretty verbose format, so - this being a Lisp example - we could probably save some typing if we represented the data as an S-expression. The above XML would become something like this:
(Term "slick"
(PartOfSpeech "adj"
(Definition
"impressive."
)
(Definition
"smart."
)
)
)
But that's an idiosyncratic style.So, let's lowercase the node types, use hyphens rather than camelCase, and remove the unnecessary line breaks. Now the data looks like this:
(term "slick"
(part-of-speech "adj"
(definition "impressive.")
(definition "smart.")))
Great. We've got our data.Now we need to write the Lisp code to convert that S-expression data into the appropriate HTML output.
We'll need some Lisp functions to handle the nodes and their attributes (such as the definition text and part of speech) and write the HTML for them. We could use an S-expression parser library to load the data, and then walk through it and call those functions. But that's not necessarily the best way. We can simplify it by creating exactly 3 functions that take some arguments and output HTML: term, part-of-speech, and definition.
Since Lisp code is - like the data - also represented as S-expressions, once we've written those 3 functions, the data is literally executable Lisp code.
Notice, the end result is just data, as terse and minimal as possible. But to act on (aka "interpret) that data, he wrote functions called "term", "part-of-speech" and "definition."
So now, that data is code. Code is data and data is code.
Hmm... it might work if I use some sort of global parameter: I first "execute the data" (damn!) with the output type set to HTML and then do it again with an output type of JSON.
http://docs.hylang.org/en/latest/language/api.html?highlight...
I'd say it's probably worth that cost, if used judiciously.
Soviet-era authority figure: "Western-style freedom has its good points---if applied judiciously".
If you're a proper Lisper, you use macros like it's going out of style, and other proper Lispers love your code for it.
All programs have their own dictionary of whatever it is they define, whether it be macros or variables. You can no more understand a function call just by looking at it than a macro call. (Should functional decomposition be introduced "judiciously" into large, monolithic blocks of code that have everything "at a glance" in one place?)
The net result, at least for me, is that I get spoiled and then it is hard for me to go back 'more primitive ways'. :)
Firstly, there rigid surface syntax which customizes the look of every macro at the character level. For instance, in C, the do ... while(); loop must have a trailing semicolon. (No Lisp macro has such requirements.)
Secondly, that surface syntax translates to a limited set of abstract syntax tree forms which is not extensible.
Lisp macros open that up. The outer layer of varnish is stripped away, so any conceivable abstract syntax tree form has a notation; you do not have to invent new character-level surface syntax in order to work with a new form. And then, custom recognizers for arbitrary forms can be written by the language users, which do tree to tree transformations.
So then how you use these things once you have them is the same way that yu use the features of programming languages that you know.
E.g. loop is a macro in Lisp. We use it like this:
[1]> (loop for x from 1 to 10
for a = 2 then (* 2 a)
collect (list x a)))
((1 2) (2 4) (3 8) (4 16) (5 32) (6 64)
(7 128) (8 256) (9 512) (10 1024))
Someone wrote the loop macro, so in this situation I'm just a user. I don't care whether this is a macro, or built-in to the language like "foreach x in list do".When I use loop, I'm benefiting from macro-writing.
The benefits are far-reaching. For instance, language experimentation takes place in the user base, not behind the closed doors of an ivory tower (ISO committee or whatever). Language ideas are packaged as code and shared around.
Technical problems turn into social problems, as someone noted.
And? This is true of code in languages without macros, too. You have too learn all the vocabulary, all the types they use, all the functions, all the structure of the program— macros are just a tool for taking these domain-specific things and packing them into a denser syntactic abstraction. A well-written macro improves readability in both the short and long terms.
I mean, say I write a couple of macros to deal with a database and I write code like
(with-sql-connection ("localhost" ...)
(select *
from "customers"
where (= "lastname" "Smith")))
Do you really think that's less readable than the nonsense you'd have to write a typical "framework," or worse, building the command string by hand? When reading other people's code you now effectively
have to learn what "language" they use too.
That's well said, and in fact it's not uncommon to talk about Lisp's capacity for crafting the language to solve the problem at hand.Paul Graham's essay "Programming Bottom-Up" explains it really really well:
"Experienced Lisp programmers divide up their programs differently. As well as top-down design, they follow a principle which could be called bottom-up design-- changing the language to suit the problem.
In Lisp, you don't just write your program down toward the language, you also build the language up toward your program. As you're writing a program you may think 'I wish Lisp had such-and-such an operator.' So you go and write it. Afterward you realize that using the new operator would simplify the design of another part of the program, and so on. Language and program evolve together. Like the border between two warring states, the boundary between language and program is drawn and redrawn, until eventually it comes to rest along the mountains and rivers, the natural frontiers of your problem.
In the end your program will look as if the language had been designed for it. And when language and program fit one another well, you end up with code which is clear, small, and efficient."
http://www.paulgraham.com/progbot.html
On the other hand, this really hurts readability.
As others have pointed out, no more than unfamiliar classes and so forth.In any language, you can think of programming as building mini languages to solve problems. You have nouns and verbs - types/classes/instances and methods/functions/operators. Lisp gives you those parts of speech and also lets you manipulate the fundamental grammar as well!
Abstraction generally gives up flexibility to obtain conciseness. Certainly a balance must be struck, but "not flexible enough" has caused me vastly more pain than "not concise enough". As a consultant who frequently wades into other people's code, I generally consider metaprogramming to be a scourge.
Paul Graham addressed this in On Lisp (page 59) [0]:
>So yes, reading a bottom-up program requires one to understand all the new >operators defined by the author. But this will nearly always be less work than >having to understand all the code that would have been required without them. >If people complain that using utilities makes your code hard to read, they >probably don’t realize what the code would look like if you hadn’t used them.
>Bottom-up programming makes what would otherwise be a large program look >like a small, simple one. This can give the impression that the program doesn’t >do much, and should therefore be easy to read. When inexperienced readers look >closer and find that this isn’t so, they react with dismay.
>We find the same phenomenon in other fields: a well-designed machine may >have fewer parts, and yet look more complicated, because it is packed into a >smaller space. Bottom-up programs are conceptually denser. It may take an effort >to read them, but not as much as it would take if they hadn’t been written that way.
Can be said of anything so it really doesn't say anything at all.
This is could be a good criticism in theory, in practice
you can observe how it works out. Fukamachi uses @ everywhere, attila-lendvai uses his def-star library ej (def (class foo) ...) instead of (defclass foo ...), some people use iterate, etc and all is good.
People can write shit code sans macros no problem. I'd rather have them than don't. After all macros embody the whole point of programming[0]
[0]: http://axisofeval.blogspot.com/2011/05/why-of-macros.html
Author doesn't mention macros explicitly, but I think the above quote is referring to them implicitly.
I'm writing a hy-like lisp language that compiles to lua. A lot of features (Simple OO, list/dict comprehensive etc.) are written in macros.
https://github.com/larme/hua/tree/master/hua/core
On the other hand, they may be difficult to debug.
Also when you learn some Lisp, you start to realize how often people are greenspuning[0] things in their projects.
One thing I __really__ miss from working in lisp is the idea that I can reload things in the repl. In Python, once I've imported something, I can't really redefine it without pasting in the definition, which makes iterating on a class definition much harder. In Lisp, I can hit a key in my editor and the running REPL gets the new definition, and I can start working with it (or rewriting tests, etc).
The power of the REPL in lisp is __amazing__. I love me some IPython (it's awesome), but there just isn't the same tight integration between that and a running system. The "default" Python likely has all the tools you need to do that, but it just isn't presented as the Way you Do It.
Django's auto-reload when code changes is an example of this. The trouble is, I can't get to a REPL easily within that, without invoking ipdb. I don't know how to integrate my editor with the Python process in a similar way, etc.
All that said, I still love coding in Python. Hy makes me excited, but then I just started writing python-with-parens and wasn't sure what I had gained. :)
0: I'm sure there is someone who can give a counterexample, but I cannot thnk of any.
In [1]: %load_ext autoreload
In [2]: %autoreload 2
In [3]: from foo import some_function
In [4]: some_function()
Out[4]: 42
In [5]: # open foo.py in an editor and change some_function to return 43
In [6]: some_function()
Out[6]: 43
It's nothing like a proper lisp repl, but you can sorta do this in vanilla python too, if you don't mind some annoyances. `reload` reloads a module:
>>> import mymodule
>>> print mymodule.myfunction()
3
>>> reload(mymodule)
>>> print mymodule.myfunction()
5
Downside is you have to use the module, `from mymodule import function` won't reload.
The sage version, and maybe this is backported to ipython by now, I don't know, you can do an %attach on a file and it gets reloaded into the workspace every time it changes.
Lisp(s) are certainly better than Python in every way, except when it comes to successful projects completed.
Note that you can program the CL system by expressing yourself in Python:
https://common-lisp.net/project/clpython/
Common Lisp is not only a language, but also a platform (analogous to Mono or JVMs). It has a model of computation: programs expand fully down to a set of special forms, which then compile. You can build languages on top of this.
(defmacro unless (test &body body)
`(if (not ,test) ,@body))There are many more examples of macros that solve real world problems, such as writing a compiler for an embedded DSL that is tuned to solving your real problem that allows expressivity and brevity that you would never see without the use of macros.
And making maintenance more difficult (aren't you re-inventing a new language with macros?)?
Where does the "First rule of the macro club" coming from? When should you break it?
No. How would that be the case?
> And making maintenance more difficult
If used poorly, sure; the same is true of most features of most languages.
> (aren't you re-inventing a new language with macros?)
You are extending the existing language with them, much as you are when using a language with user-definable functions rather than only builtins.
No. How would macros break homoiconicity? They expand into atoms and lists (and other datatypes), the same stuff of which macro-free programs are made.
>And making maintenance more difficult?
No. Unless you intentionally write unmaintainable macros. It's the same as if you write unmaintainable functions, classes, etc. They're just abstracting a different thing— syntax.
>aren't you re-inventing a new language with macros?
No, you're expanding the language; you're just expanding the grammar instead of the vocabulary.
>Where does the "First rule of the macro club" coming from? When should you break it?
What is the "first rule of the macro club?"
You should break that rule only when the behavior can’t be written as a function, such as these cases:
• The call needs to avoid evaluating its arguments. For example, the `if` built into the language is sometimes defined as a macro.
(if (= (+ 2 2) 4)
(print "math works")
(print "math is broken"))
If `if` were a function, it would first print both statements, and then return the return value of `print` in whichever branch. By making `if` a macro, it can avoid evaluating the branch that is inapplicable.• The call relies on information about the environment only available at compile-time. Perhaps the macro reads a configuration file on the developer’s computer to decide how to set something up.
• You have profiled the program and determined that it is better to run the function at compile-time. For example, you might want to make `(regex "[a-z][a-z0-9]+")` compile the string to a regular expression at compile-time instead of run-time.
I think it would be more appropriate to use a compiler macro here.
If used right, macros make things much more maintainable. If you have a hundred nearly-identical codeblocks, where only (say) a string constant is varying, and suddenly you need to change what those blocks do, bam, you've got a hundred blocks to change. If those blocks had been refactored with a macro, all you have to do is change the macro once. It also prevents the new guy from coming and doing a bandaid fix to line #72 making it slightly different from the 99 lines around it and making your life a living hell.
if ( key == "hitpoints" ) {player.hitpoints = value; return;}
if ( key == "mana" ) {player.mana = value; return;}
Those "return"s make it rather awkward to use a function. At best, said function would have to return a bool and you'd end up with something like
if ( maybe_assign( key, "hitpoints", &player.mana ) ) return;
which hardly gains you anything and in fact reduces readability a fair amount.
I listed some situations where you need a macro in my comment that explains the “first rule of the macro club” you asked about: https://news.ycombinator.com/edit?id=9513988
only if you don't look too closely
Look as closely as you'd like. :) what about break and continue? They are usually
supported by native foreach construct but are
difficult to build with macros..
For break, DOLIST uses return. I haven't worked with Lisp in some time, so I don't remember if it has a dedicated continue. But a continue is just a break in a loop that doesn't loop. Or a GOTO by another name. Or a jump to a particular case in a switch.But if your looping macro uses a native looping construct or another macro that supports break and continue, then your looping macro will inherit that support, provided that you're careful when writing the macro to do nothing that will break it.
If your looping macro doesn't use a construct that supports break and continue, then you're still in luck. Continue I described above. Like continue, break is also GOTO by another name. You've got TAGBODY, GO, CALL/CC, etc.
Why do you think that supporting break and continue in macros is difficult?
In many languages, emulation of control loop do not support break and continue so I thought that this was the case also here, but apparently I'm wrong, sorry for my 'too quick' post and thanks for the correction.
probably, one evil thing is you have to deal with every other's abstraction and it will make you frustrated when there is a large codebase and a deadline.
* Another programmer's 15 function API, and a document on how to use it properly?
* Or another programmer's 15 function API, along with three macros which use the API properly, and capture all the scenarios I need based on a couple of examples.
- Does the machine write it, using a reliable syntax rule loaded into the compiler (implemented as a macro); or
- Does the programmer, by hand (or with textual preprocessing, copy and paste, IDE help, ...).
Macros can be as smart as you want them to be.
Not all macros are well written is a poor argument; not all anything is well written ... so don't use anything!