1 line
2.3 KiB
Plaintext
1 line
2.3 KiB
Plaintext
<!-- SC_OFF --><div class="md"><p>Many have suggested adding a lambda reader construct to Emacs Lisp: something like <code>#(princ $1)</code>, which would be translated to <code>(lambda (x) (princ x))</code>.</p> <p>Well, it turns out that you can (ab)use the existing reader constructs for this purpose. Specifically, <code>,x</code> and <code>,@x</code> are translated to <code>(\, x)</code> and <code>(\,@ x)</code>, which are without meaning outside of a backquoted list.</p> <p>That means that it is legal to define and use <code>\,</code> as a function or macro:</p> <pre><code>(defmacro \, (body) "Return an anonymous function. In BODY, symbols of the type $N, where N is a non-zero, positive number, represent positional arguments. $* represents a list of optional remaining arguments. ,(+ $1 $2) expands to (lambda ($1 $2) (+ $1 $2)). See `lambda'." (let ((total 0) rest) (cl-labels ((search (form) (if (consp form) (progn (search (car form)) (search (cdr form))) (if (eq form '$*) (setq rest t) (let ((s (prin1-to-string form))) (if (string-match "^\\$\\([1-9][0-9]*\\)$" s) (let ((n (string-to-number (match-string 1 s)))) (setq total (max total n))))))))) (search body)) `(lambda ,(append (cl-loop for n from 1 upto total collect (intern (format "$%d" n))) (and rest '(&rest $*))) ,body))) </code></pre> <p>With this macro, you can replace</p> <pre><code>(mapcar (lambda (x) (with-output-to-string (princ x))) objects) </code></pre> <p>with</p> <pre><code>(mapcar ,(with-output-to-string (princ $1)) objects) </code></pre> <p>If you want your lambda to accept an unlimited number of arguments, use `$*':</p> <pre><code>(advice-add 'some-function :before ,(dolist (x $*) (message "%s" x))) </code></pre> <p>What are the downsides? Strictly, there is only one. The docstring for the macro above will not be displayed in Emacs' help system, which will always display the built-in information about <code>,</code>.</p> </div><!-- SC_ON -->   submitted by   <a href="https://www.reddit.com/user/quote-only-eeee"> /u/quote-only-eeee </a> <br/> <span><a href="https://www.reddit.com/r/emacs/comments/r4b3au/working_implementation_of_shorthand_lambda_syntax/">[link]</a></span>   <span><a href="https://www.reddit.com/r/emacs/comments/r4b3au/working_implementation_of_shorthand_lambda_syntax/">[comments]</a></span> |