Reputation: 309
In the book Let Over Lambda: Chapter-4 cl-ppcre section, a read macro with dispatch characters #~ is implemented to get the regex matching and substitution syntax similar to Perl. The function used to implement the read-macro is |#~-reader|.
This function is implemented using the two macros defined earlier :
I was wondering, besides educational purpose, what is the need to use macros for the above two tasks ? I implemented a variant using simple functions :
(defun match-mode-alt (args)
`(lambda (x) (cl-ppcre:scan ,(car args) x)))
(defun subst-mode-alt (args)
`(lambda (x) (cl-ppcre:regex-replace-all ,(car args)
x
,(cadr args))))
I then simply used these functions instead of corresponding macros and it seems to work fine. Because these are functions there is no need for double quasiquote, once-only macro and other shiny stuff which are obviously harder to implement and debug compared to simple functions in actual programs.
In this particular case, any benefit macros have over functions ? It cant be efficiency because these functions are ultimately end up being called during reading phase (via read-macro) so there is no real run-time cost.
Upvotes: 4
Views: 158
Reputation: 1768
I think, they should have used macros for the sake of example solely... because constructing the lambda
around cl-ppcre:
calls can indeed be completed during the reading phase, provided that the reader macro doesn't make use of any other form than the string, that follows the macro character. In general, the golden rule states, that macros should be avoided in cases when an ordinary function can be used. Sometimes (for example, when it's necessary to control the evaluation of the arguments) macros are inevitable, but it this particular case function is sufficient.
Upvotes: 2