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?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)))))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.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.
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).
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.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.
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'. :)
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))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.
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.
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.
The old way of lisping is to prototype in lisp, then build in a "real" language (c/java). However nowadays the lisp implementations (CCL/SBCL specifically) are fast/advanced enough to the point where you can prototype in lisp, then just use add some type specifiers and boom there's your app. Hell, with ECL you can even embed your lisp program into another one, while still achieving compiled speeds.
Compare that to a similar problem I had with a C# app we had. For that I had to stick in a load of logging code, check it in then wait half an hour for the CI server to deploy before running and checking the logs.
Working with a Lisp was much more pleasurable.
EDIT: I suppose what I'm asking is whether you could elaborate more on what this looks like, in practice.
Basically I have a horizontally split 'screen' session, code in the top and repl in the bottom, and I just ctrl+[c+c] to send paragraphs from the top to the bottom. I don't remember if vim-slime comes with it or if I augmented it, but I also do ctrl+[c+f] to send the current Lisp/Clojure form, ctrl+[c+l] to send the current line... Or just ctrl+a+tab to switch screen windows and type in the REPL directly.
If you do like vim, slimv is a really great option for lisping.
By that same token, a Volkswagen Beetle is a badly-designed boat.
XML was never designed as a data serialization format. It's a markup language. It was designed to sprinkle structure and metadata into large human-readable plaintext documents.
Likewise, JSON is a subset of a general-purpose programming language's literal notation that happened to be very fast to parse in a browser by virtue of the browser implementing that language.
Personally, I don't think s-exprs are a particularly great serialization format either. The problem is that there's no one-sized-fits-all for serialization. What we value is brevity, but basic information theory tells we can only make expressing some things more terse by making others more verbose.
When you say some format is badly-designed, all you're really saying is that it isn't optimized for the kinds of data you happen to want to serialize.
Those two things are not mutually exclusive.
> Likewise, JSON is a subset of a general-purpose programming language's literal notation that happened to be very fast to parse in a browser by virtue of the browser implementing that language.
That's true. That is not in conflict with anything I said.
> The problem is that there's no one-sized-fits-all for serialization.
No, that's not true. S-exprs really are a global optimum in the space of serialization designs. All the alternatives are logically equivalent to S-exprs but with extra punctuation that makes them arguably harder to read, but inarguably harder to write. That is why S-exprs are the ONLY syntax ever designed (some would say "discovered") by humans that has been successfully used to represent both code and data.
> Those two things are not mutually exclusive.
I beg to differ. I just replied to someone else about this: https://news.ycombinator.com/item?id=9509110
I agree with your last paragraph, though. There is a timelessness about S-expressions.
As a side point, I would add that the distinction between strings and symbols is important, and neither XML nor JSON has it.
But I am completely nonplussed at your assertion that markup and serialization are mutually exclusive. There is a 1-to-1 correspondence (actually multiple 1-to-1 mappings) between XML and S-expressions, so whatever you can do with sexprs you can do with XML modulo some trivial transformation. The ONLY difference is in the amount of punctuation and redundancy.
> the distinction between strings and symbols is important
Yeah, that's a good point.
> neither XML nor JSON has it
That's not quite true. It's not that JSON doesn't have symbols, it's that Javascript doesn't have symbols. And XML doesn't have symbols natively, but you can easily gin them up yourself, e.g. <symbol>foo</symbol> or <symbol name=foo />.
Usually example where I see people rewrite XML to s expressions (like in this thread) are very lossy -- its easy to be pretty by throwing away most of the information!
I'm not sure what example in this thread you consider to be throwing information away - in a case like
<Term term="slick">
where the attribute name is clearly redundant and exists only to satisfy the syntax, nothing is lost in the transformation to (term "slick"You haven't looked hard enough. Mappging XML to sexprs is trivial:
<tag value=attr ...>content</tag>
-->
((tag value attr ...) content)
http://eli.thegreenplace.net/2012/03/04/some-thoughts-on-jso...
However, Sexps easily support hash tables.
Example:
$ txr -p "(let ((x (hash))) (set [x 'a] 1) (set [x 'b] 2) x)"
#H(() (b 2) (a 1))
Here I have chosen a "hash capital H" syntax for hash tables. The first part () has the hash attributes (there are none, so it's an eql-equality-based hash table, with strong keys and values). Then, entries consisting of two element list pairs give the keys and values.This hash prefix notation builds on existing Lisp concept of using simple prefixes to distinguish various kinds of objects. In Common Lisp we have:
#(1 2 3) ;; this is a vector
#C(3.0 4.9) ;; this is the complex number 3.0 + 4.9i
The scanning is very simple: you just recognize the prefix like #C( or #( and then recurse into the scanner for list elements that stops at a closing parenthesis.No whitespace is allowed: it cannot be # (1 2 3) or # C (3.0 4.9).
TXR Lisp above not only reads back the hash notation, so it can be used as a literal, but allows backquoting over it. We can splice keys and values into the syntax to produce a hash table:
$ txr -p "(let ((keys '(a b c)) (vals '(1 2 3)))
^#H(() ,*(zip keys vals)))"
#H(() (c 3) (b 2) (a 1))But the reverse is not necessarily true. It's possible for a badly-designed serialization format to be longer in all cases than some other format.
And, in particular, I suspect that for the same data, XML is longer in all cases than S expressions.
This matches my experience. The barrier between application and language/compiler development disappears, and instead you get a rich new feedback loop between the two. Overall complexity decreases (<-- a big deal), and many hard things become easy.
The effects of this compound over time, so what starts as a mere notational difference turns into a deeply different programming style, one I find so enjoyable that doing without it feels like going back into a straitjacket after escaping.
That sounds really powerful and interesting, but wondering how often is that used in practice? I can imagine maintaining and understanding a large self-modifying program like that could get a bit complicated for a team.
It really shines on apps with a lot of state (such as a game) where normally you'd have to quit, change the code, recompile, run the app, and reproduce the original state as closely as possible. With lisp you can just replace the function you are debugging while the app is running.
That said, lisp can be used for self-modifying programs pretty easily. The idea that the default data structures it manipulates are the same as the code itself makes it easy to build data structures with the purpose of being evaled (not saying this is ever a good practice).
And essentially, macros are self-modifying programs that run before the actual program runs.
I do it too in python via ipython. Maybe what the author meant is "Why exploratory programming using a REPL is great".
A good example would be the Emacs text editor. You can use it to modify the source of Emacs itself while it is running. You never need to reboot it to test new code because you can interactively evaluate new functions and replace existing ones.
As for working in teams, usually each developer runs their own REPL instance isolating them from the changes made by other developers. You can still pull a coworker's commit and evaluate it into your running instance without even restarting the program under development.
Modifying a running program to make a change as you develop it is an incredible speedup, relative to (recompiling and) restarting all the time, and even relative to reloading whole changed files.
Having used the old Smalltalk and Oberon environments, sadly not Lisp ones, I really thing many still don't get it.
Like so. I think it could catch on. And you get rid of so many round bracket block delimiters (at least for S-expressions on the same level. for nesting you obviously need them) that it makes reading a lot easier. Also make the language modal and have the default be the indicative mood. Maybe replace "." with "?" for interrogative mood? Maybe elide ".)" to ")" as another optimization?
(define-record-type omap-entry
(make-omap-entry key item next prev)
omap-entry?
(key omap-entry-key set-omap-entry-key!)
(item omap-entry-item set-omap-entry-item!)
(next omap-entry-next set-omap-entry-next!)
(prev omap-entry-prev set-omap-entry-prev!))
would be written like this? (define-record-type omap-entry
make-omap-entry key item next prev.
omap-entry?,
key omap-entry-key set-omap-entry-key!.
item omap-entry-item set-omap-entry-item!.
next omap-entry-next set-omap-entry-next!.
prev omap-entry-prev set-omap-entry-prev!)
(To mark `omap-entry?` as being a value, not the S-expression `(omap-entry?)`, I decided to place a comma after it instead of a period. The alternative is requiring no punctuation and making newlines significant.)Well, I suppose it does look better.
However, the idea is of limited applicability. While looking through the example project (https://github.com/axch/test-manager), I had trouble finding some code where this would actually be useful – most code has too much nesting.
That’s why I prefer another solution for removing excess parens from Lisp syntax: making whitespace significant. It improves the syntax in cases where your periods would help, and it applies in additional cases as well.
“Sweet-expressions” (http://readable.sourceforge.net/) is an implementation of that. Here is the above code ran through the `sweeten` tool to convert it to sweet-expressions:
define-record-type
omap-entry
make-omap-entry key item next prev
omap-entry?
key omap-entry-key set-omap-entry-key!
item omap-entry-item set-omap-entry-item!
next omap-entry-next set-omap-entry-next!
prev omap-entry-prev set-omap-entry-prev!
Absolutely no parentheses necessary, while still preserving homoiconicity. You don’t even have to remember the `)` at the end of the last nested line. And I chose this example code to look good with your idea – when the code has more nesting, sweet-expressions look even better.About the interrogative mood `?` you describe: it might simplify `if` statements. But that would require removing the convention where boolean-returning functions have a name ending in `?`, such as `omap-entry?` in the example. It’s a tradeoff.
I must press, well-designed according to what measure? OP presents the well-designed serialization format as a strict positive instead of the truth: a tradeoff compared to other unnamed qualities.
I worked at a large e-commerce retailer for a few years, one that you might have heard of or even purchased something from. I had the experience of building a few systems in Lisp and also in a few mainstream imperative languages. It was tough and really lonely even though I had real success.
With Lisp I could do things that whole teams could only dream of in Blub and in much shorter periods of time.
The problems weren't really technical but more psychological and social when it came to Lisp. Big problems. I wasn't very successful in resolving many of them.
I still use Lisp here and there but have been drawn to the ML family in the past few years. Strong static type systems got a hold of me for better or worse.
All languages suck, it's just the degree that differs.
When I first started programming, and for a long while, I'd think top down. What do I got? Then, how can I iterate through that to do the operations I want and then build up what I need?
With lisp, the ability to reuse code in closures is so easy, you can afford to think a different way. What are the most basic, clean and simple, operations I need to do? (not necessarily in order I need to do them) This includes conversion, summing results, iterating through a structure, etc.
After writing functions for those, you can quite easily plug them all together without much thought.
You end up with code that is non-redundant, clear, reusable, easy to debug, and flexible.
And to be honest, I am not really interested in how hard it is to write a compiler for the language I use.
user=> (-> "a b c d"
.toUpperCase
(.replace "A" "X")
(.split " ")
first)
It is trivial to write the macro in other Lisps.I've heard good things about MOCL but haven't tried it myself, and I know getting ECL working on mobile is an uphill battle (but achievable if you have the time). ECL switched maintainers recently, so maybe mobile is something they will focus on in the future.
I run Linux on my web servers but develop from a Windows desktop. CCL works great on both.
I don't think the developers have worked around that, though I have seen some conversation about it in the past. My limited Google searches on the subject today didn't suggest that anything has changed since the last time I looked at it.
Edit:
Oh, duh, I already said all of this about 4 1/2 years ago:
https://news.ycombinator.com/item?id=1804415
Visiting the system requirements page again suggests the limitation still exists:
That's not usually a showstopper for me, though.
The current public release TXR Lisp still has an embarrassingly shoddy implementation of "places": expressions which not only evaluate, but serve as assignable locations. I implemented most of the place-manipulating operators (set, inc, push, ...) as special forms, and only a small repertoire of places is hard-coded in the interpreter. (And that, by the way, creates one of the impediments against going to a compiler.)
I have thrown all that out and created a macro-based system for places. Instead of copying the Common Lisp one, I drummed up something new.
Common Lisp lets programmers register assignment places as "setf expanders" which return five values: lists of temporary variables, access and store forms and such. (Google for "CLHS get-setf-expansion").
I have taken a somewhat different, though necessarily closely-related approach. The creator of a new place provides two or three functions. These functions take a place and a piece of code, and wrap it with macrolets for accessing the place. These macrolets are given names that the caller specifies. Of course, I have a macro for writing these functions as a capsule.
The three functions provide a way for handling the access and update of a place, a simple store to a place without an access, and the deletion of a place.
This third item is new. In TXR Lisp, there is a del operator: a place can be vaporized. Not all places support deletion, but many do. For instance you can do (del [some-vector 3]) to delete an item from a vector. Or a range. Hashes support deletion. (del (car x)) works: what happens when you delete the car of a cons cell is that the cdr is popped, and the popped item is transferred into the car. Thus if x holds (1 2 3), the (2 3) part is popped to produce (3) and the 2 moves into the car, resulting in X holding (2 3). (I just realized that we need place insertion to complement place deletion!)
Here is how a (vecref <vector> <index>) place is defined:
(defplace (vecref vector index :whole args) body
(getter setter
(with-gensyms (vec-sym ind-sym)
^(rlet ((,vec-sym ,vector)
(,ind-sym ,index))
(macrolet ((,getter () ^(vecref ,',vec-sym ,',ind-sym))
(,setter (val) ^(refset ,',vec-sym ,',ind-sym ,val)))
,*body))))
(ssetter
^(macrolet ((,ssetter (val) ^(refset ,*',args ,val)))
,*body))
(deleter
(with-gensyms (vec-sym ind-sym)
^(rlet ((,vec-sym ,vector)
(,ind-sym ,index))
(macrolet ((,deleter ()
^(prog1 (vecref ,',vec-sym ,',ind-sym)
(replace-vec ,',vec-sym nil
,',ind-sym (succ ,',ind-sym)))))
,*body)))))
[[ Digression: what is rlet in the above?The rlet macro is something I just invented days ago. It is like let, but it detects and optimizes cases when a symbol is bound to another symbol, and turns these into symbol macrolets. Demo:
$ ./txr -p "(sys:expand '(rlet ((a b) (c (form))) (list a b c)))"
(let ((c (form))) (list b b c))
Look, the (a b) disappeared in the form expansion, and b was replaced by a. That's because the macro expansion is this: $ ./txr -p "(macroexpand '(rlet ((a b) (c (form))) (list a b c)))"
(symacrolet ((a b)) (let ((c (form))) (list a b c)))
rlet also propagates simple constants, as shown by the variable d: $ ./txr -p "(sys:expand '(rlet ((a b) (c (form)) (d 42)) (list a b c d)))"
(let ((c (form))) (list b b c 42))
Of course, let can only be replaced by rlet in certain circumstances, when we don't rely on the binding actually providing storage semantics. Above, we can only replace a with b, if a is not assigned anywhere. And since d is replaced with 42 blindly, it cannot be assigned.Obviously, rlet is something you don't need if you have an optimizing compiler which eliminates useless temporary variables and propagates constants! I just wanted nicer expansions from the places system.]]
So anyway, the defplace creates three functions which provide advice for how to correctly access, update and delete a place. They wrap this advice, which takes the form of local functions or macros, and any additional lexical definitions they need, around a supplied piece of code, and that code can refer to that.
Here is how this advice is used, in the implementation of the swap operator. This shows you the real beauty of the system, because we can write a completely robust swap, but we don't have to use anything resembling CL's get-setf-expansion and its five cumbersome return values:
(defmacro swap (place-0 place-1 :env env)
(with-gensyms (tmp)
(with-update-expander (getter-0 setter-0) place-0 env
(with-update-expander (getter-1 setter-1) place-1 env
^(let ((,tmp (,getter-0)))
(,setter-0 (,getter-1))
(,setter-1 ,tmp))))))
What is the env doing there? We have to pass the macro-time environment down, because places can be macros! For instance what if we do (swap a b), but a is actually a lexical symbol macro for (car x) and b is something similar: the with-update-expander macro will take care of expanding these places, so it fetches the correct advice for the expanded places.So note how we have a completely naive looking pieces of code, a three point swap:
^(let ((,tmp (,getter-0)))
(,setter-0 (,getter-1))
(,setter-1 ,tmp))))))
All we did was generate some gensyms, use a couple of macros to obtain the place-accessing expertise from some generated lexical helpers, and then wrote a straightforward swap. $ ./txr -p "(sys:expand '(swap a b))"
(let ((#:g0044 a)) (sys:setq a b) (sys:setq b #:g0044))
$ ./txr -p "(sys:expand '(swap (car c) (cdr c)))"
(let ((#:g0044 (car c))) (sys:rplaca c (cdr c)) (sys:rplacd c #:g0044))
$ ./txr -p "(sys:expand '(swap 1 2))"
./txr: unhandled exception of type eval-error:
./txr: during expansion at string:1 of form (swap 1 2)
./txr: message: form 1 is not syntax denoting an assignable place
$ ./txr -p "(sys:expand '(swap [f x] [g y]))"
(let ((#:g0067 [f x])) (let ((#:g0056 [g y])) (let ((#:g0044 #:g0067))
(sys:setq f (sys:dwim-set f x #:g0056)) (sys:setq g (sys:dwim-set g y #:g0044)) #:g0044)))
Note the [] notation is completely generic, so f and x could be lists (or vectors, hashes, strings). In this case, f and x are themselves expected to be places. Thus [f x] must be a place, and f also must be a place. The reason is that if we manipulate a list, we may have to assign the new list to the old variable. In general, sys:dwim-set could cons up a new list.So in summary, Lisp is always fresh and keeps me interested in hacking. Even old things (solved problems like assignment places) can be looked at in a new light.
Check out this recursive implementation of shift, which is like Common Lisp's shiftf:
(defmacro shift (:env env . places)
(tree-case places
(() (eval-err "shift: need at least two arguments"))
((place) (eval-err "shift: need at least two arguments"))
((place newvalue)
(with-update-expander (getter setter) place env
^(prog1 (,getter) (,setter ,newvalue))))
((place . others)
(with-update-expander (getter setter) place env
^(prog1 (,getter) (,setter (shift ,*others)))))))
$ ./txr -p "(sys:expand '(shift a b c d))"
(prog1 a (sys:setq a (prog1 b (sys:setq b (prog1 c (sys:setq c d))))))This perfectly illustrates both the power and danger of Lisp; also known as “The Lisp Curse”¹
This line doesn't hold on its own but as the ending of the article it was very powerful.
I had heard that extra power can make it easier to do things wrong, but the idea that extra power can cause problems even when you do things right is fascinating.
There is also the famous essay "Beating an average" and this very site as a walk of their talk.
There are also SICP and PAIP and Norvig's Lisp Style Guide.
Read the best thinkers.