by Xophmeister · 11y ago · 0 comments
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.
"if I have a non-strictly evaluated language with higher order functions, do I still need macros?"
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...
Depriving a Haskell programmer of the ability to define new macros is going to hurt a whole lot less than depriving a Lisp programmer of the same.
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.
That definition of "macro" equivalent with "phrase structure rule in your functional language's compiler" which takes the input structure and generates whatever code brings about the lazy semantics (which is not inherent in the x86 instruction set or what have you).
> example where these "macros" are not enough
An example is any instance of language extension where, say, the maintainers of the compiler for a functional language have to ship a new compiler to the users to get them to use the new feature.
Functional languages with lazy evaluation are not finished, right? They are developed actively.
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.
(def is-type (proc (x t) (eq? (type x) t)))
(is-type 5 'int)
But it's nice to have single-parameter ones for FP list stuff. I suppose that 2-parameter version could have their order swapped and do partial application on top of it.Anyway, was just sharing something I had fun making. No language wars intended.
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.