I have been using Clojure alot recently but I still don't understand what functionality I do not get that common lisp reader macros provide. Can explain explain this to me in simple terms?
问题:
回答1:
In short, reader macros provide you with the ability to redefine the programming language's syntax within some delimited context.
For example, you could implement regular expression literals (e.g. #"pattern"
) yourself given reader macros. Without them, you would be forced to properly escape regular expressions in string literals passed to re-pattern
.
BTW, while there are no public Clojure APIs for modifying the reader, it's not impossible, as illustrated in these posts:
- http://briancarper.net/blog/449/clojure-reader-macros
- http://fulldisclojure.blogspot.com/2009/12/how-to-write-clojure-reader-macro.html
回答2:
A simple example. Common Lisp has a different reader syntax for vectors #() instead of []. But with the ability to create custom reader macros you can have a reader macro that traslates [2 3 4 5] to a vector in Common Lisp as well.
Since most users won't be aware of the meaning of reader macros one has created they are rarely used and to avoid the confusion altogether Rich Hickey decided to remove the ability to have user defined reader macros in Clojure. Clojure, however, has predefined reader macros - quote, vector, regex, map, etc
回答3:
In Common Lisp the reader is user extensible with reader macros. The reader is responsible to read s-expressions. S-expressions are an external textual syntax for Lisp's data types like numbers, strings, symbols, lists, conses, structures, arrays, characters, ...
The reader is not responsible for the syntax of the programming language Lisp - just for s-expressions.
Thus the main purpose, from the point of the user, for reader macros is to extend or change the syntax of s-expressions. For example the user can add textual syntax for various CLOS classes (like URLs, ...), hash-tables, special identifiers, new number types, ...
Sometimes it is also used to embed syntax of other languages/syntax, which have different rules to form tokens: embedded SQL, embedded C, infix expressions, embedded calls to Objective C, embedded rule languages, embedded XML, embedded JSON and more.
Another use is to allow the user to have additional control over the s-expressions, the reader actually reads. For example conditional feature expressions.
Thus user programmable reader macros allow the user to customize the reader with regard to the above described functionality. One can imagine that this is useful for those users, who want to customize the language at a data-syntax/token level, but it adds another layer of complexity.