emacs/var/elfeed/db/data/64/64f430e9a9a2aa680bbb0fa3bab1fe173302d0ab
2022-01-03 12:49:32 -06:00

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) &quot;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&#39;.&quot; (let ((total 0) rest) (cl-labels ((search (form) (if (consp form) (progn (search (car form)) (search (cdr form))) (if (eq form &#39;$*) (setq rest t) (let ((s (prin1-to-string form))) (if (string-match &quot;^\\$\\([1-9][0-9]*\\)$&quot; 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 &quot;$%d&quot; n))) (and rest &#39;(&amp;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 `$*&#39;:</p> <pre><code>(advice-add &#39;some-function :before ,(dolist (x $*) (message &quot;%s&quot; 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&#39; help system, which will always display the built-in information about <code>,</code>.</p> </div><!-- SC_ON --> &#32; submitted by &#32; <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> &#32; <span><a href="https://www.reddit.com/r/emacs/comments/r4b3au/working_implementation_of_shorthand_lambda_syntax/">[comments]</a></span>