<p>I've been attempting to write a Lisp macro that would perfom the equivalent of ++ in other programming languages for semantic reasons.  I've attempted to do this in several different ways, but none of them seem to work, and all are accepted by the interpreter, so I don't know if I have the correct syntax or not.  My idea of how this would be defined would be</p>

<pre><code>(defmacro ++ (variable)
  (incf variable))
</code></pre>

<p>but this gives me a SIMPLE-TYPE-ERROR when trying to use it.  What would make it work?</p>

[{'answer_id': 65641, 'author': 'Kyle Cronin', 'author_id': 658, 'author_profile': 'https://Stackoverflow.com/users/658', 'pm_score': 5, 'selected': True, 'text': '<p>Remember that a macro returns an expression to be evaluated. In order to do this, you have to backquote:</p>\n\n<pre><code>(defmacro ++ (variable)\n   `(incf ,variable))\n</code></pre>\n'}, {'answer_id': 65657, 'author': 'Drew Olson', 'author_id': 9434, 'author_profile': 'https://Stackoverflow.com/users/9434', 'pm_score': -1, 'selected': False, 'text': "<p>This should do the trick, however I'm not a lisp guru.</p>\n\n<pre><code>(defmacro ++ (variable)\n  `(setq ,variable (+ ,variable 1)))\n</code></pre>\n"}, {'answer_id': 66863, 'author': 'user10029', 'author_id': 10029, 'author_profile': 'https://Stackoverflow.com/users/10029', 'pm_score': 4, 'selected': False, 'text': "<p>Both of the previous answers work, but they give you a macro that you call as</p>\n\n<pre><code>(++ varname)\n</code></pre>\n\n<p>instead of varname++ or ++varname, which I suspect you want. I don't know if you can actually get the former, but for the latter, you can do a read macro. Since it's two characters, a dispatch macro is probably best. Untested, since I don't have a handy running lisp, but something like:</p>\n\n<pre><code>(defun plusplus-reader (stream subchar arg)\n   (declare (ignore subchar arg))\n   (list 'incf (read stream t nil t)))\n(set-dispatch-macro-character #\\+ #\\+ #'plusplus-reader)\n</code></pre>\n\n<p>should make ++var actually <em>read</em> as (incf var).</p>\n"}, {'answer_id': 77562, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>For pre-increment, there\'s already incf, but you can define your own with</p>\n\n<pre><code>(define-modify-macro my-incf () 1+)\n</code></pre>\n\n<p>For post-increment, you could use this (from fare-utils):</p>\n\n<pre><code>(defmacro define-values-post-modify-macro (name val-vars lambda-list function)\n "Multiple-values variant on define-modify macro, to yield pre-modification values"\n (let ((env (gensym "ENV")))\n   `(defmacro ,name (,@val-vars ,@lambda-list &amp;environment ,env)\n      (multiple-value-bind (vars vals store-vars writer-form reader-form)\n          (get-setf-expansion `(values ,,@val-vars) ,env)\n       (let ((val-temps (mapcar #\'(lambda (temp) (gensym (symbol-name temp)))\n                                 \',val-vars)))\n          `(let* (,@(mapcar #\'list vars vals)\n                  ,@store-vars)\n             (multiple-value-bind ,val-temps ,reader-form\n               (multiple-value-setq ,store-vars\n                 (,\',function ,@val-temps ,,@lambda-list))\n               ,writer-form\n               (values ,@val-temps))))))))\n\n(defmacro define-post-modify-macro (name lambda-list function)\n "Variant on define-modify-macro, to yield pre-modification values"\n `(define-values-post-modify-macro ,name (,(gensym)) ,lambda-list ,function))\n\n(define-post-modify-macro post-incf () 1+)\n</code></pre>\n'}, {'answer_id': 77772, 'author': 'simon', 'author_id': 14143, 'author_profile': 'https://Stackoverflow.com/users/14143', 'pm_score': 3, 'selected': False, 'text': "<p>Semantically, the prefix operators ++ and -- in a language like c++ or whatever are equivalent incf/decf in common lisp.  If you realize this and, like your (incorrect) macro, are actually looking for a syntactic change then you've already been shown how to do it with backticks like `(incf ,x).  You've even been shown how to make the reader hack around this to get something closer to non-lisp syntax. That's the rub though, as neither of these things is a good idea.  In general, non idiomatic coding to make a language resemble another more closely just doesn't turn out to be such a good idea.</p>\n\n<p>However, if are actually looking for the semantics, you've already got the prefix versions as noted but the postfix versions aren't going to be easy to match syntactically.  You could do it with enough reader hackery, but it wouldn't be pretty.</p>\n\n<p>If that's what you're looking for, I'd suggest a) stick with incf/decf names since they are idiomatic and work well and b) write post-incf, post-decf versions, e.g (defmacro post-incf (x) `(prog1 ,x (incf ,x))  kinds of things. </p>\n\n<p>Personally, I don't see how this would be particularly useful but ymmv.</p>\n"}, {'answer_id': 241721, 'author': 'Svante', 'author_id': 31615, 'author_profile': 'https://Stackoverflow.com/users/31615', 'pm_score': 3, 'selected': False, 'text': '<p>I would strongly advise against making an alias for incf.  It would reduce readability for anyone else reading your code who have to ask themselves "what is this? how is it different from incf?"</p>\n\n<p>If you want a simple post-increment, try this:</p>\n\n<pre><code>(defmacro post-inc (number &amp;optional (delta 1))\n  "Returns the current value of number, and afterwards increases it by delta (default 1)."\n  (let ((value (gensym)))\n    `(let ((,value ,number))\n       (incf ,number ,delta)\n       ,value)))\n</code></pre>\n'}, {'answer_id': 10567794, 'author': 'Kaz', 'author_id': 1250772, 'author_profile': 'https://Stackoverflow.com/users/1250772', 'pm_score': 4, 'selected': False, 'text': '<p>The syntax <code>(++ a)</code> is a useless alias for <code>(incf a)</code>. But suppose you want the semantics of post-increment: retrieve the old value. In Common Lisp, this is done with <code>prog1</code>, as in: <code>(prog1 i (incf i))</code>. Common Lisp doesn\'t suffer from unreliable or ambiguous evaluation orders. The preceding expression means that <code>i</code> is evaluated, and the value is stashed somewhere, then <code>(incf i)</code> is evaluated, and then the stashed value is returned.</p>\n\n<p>Making a completely bullet-proof <code>pincf</code> (post-<code>incf</code>) is not entirely trivial. <code>(incf i)</code> has the nice property that <code>i</code> is evaluated only once. We would like <code>(pincf i)</code> to also have that property. And so the simple macro falls short:</p>\n\n<pre><code>(defmacro pincf (place &amp;optional (increment 1))\n  `(prog1 ,place (incf ,place ,increment))\n</code></pre>\n\n<p>To do this right we have to resort to Lisp\'s "assignment place analyzer" called <code>get-setf-expansion</code> to obtain materials that allow our macro to compile the access properly:</p>\n\n<pre><code>(defmacro pincf (place-expression &amp;optional (increment 1) &amp;environment env)\n  (multiple-value-bind (temp-syms val-forms\n                        store-vars store-form access-form)\n                        (get-setf-expansion place-expression env)\n    (when (cdr store-vars)\n      (error "pincf: sorry, cannot increment multiple-value place. extend me!"))\n    `(multiple-value-bind (,@temp-syms) (values ,@val-forms)\n       (let ((,(car store-vars) ,access-form))\n         (prog1 ,(car store-vars)\n                (incf ,(car store-vars) ,increment)\n                ,store-form)))))\n</code></pre>\n\n<p>A few tests with CLISP. (Note: expansions relying on materials from <code>get-setf-expansion</code> may contain implementation-specific code. This doesn\'t mean our macro isn\'t portable!)</p>\n\n<pre><code>8]&gt; (macroexpand `(pincf simple))\n(LET* ((#:VALUES-12672 (MULTIPLE-VALUE-LIST (VALUES))))\n (LET ((#:NEW-12671 SIMPLE))\n  (PROG1 #:NEW-12671 (INCF #:NEW-12671 1) (SETQ SIMPLE #:NEW-12671)))) ;\nT\n[9]&gt; (macroexpand `(pincf (fifth list)))\n(LET*\n ((#:VALUES-12675 (MULTIPLE-VALUE-LIST (VALUES LIST)))\n  (#:G12673 (POP #:VALUES-12675)))\n (LET ((#:G12674 (FIFTH #:G12673)))\n  (PROG1 #:G12674 (INCF #:G12674 1)\n   (SYSTEM::%RPLACA (CDDDDR #:G12673) #:G12674)))) ;\nT\n[10]&gt; (macroexpand `(pincf (aref a 42)))\n(LET*\n ((#:VALUES-12679 (MULTIPLE-VALUE-LIST (VALUES A 42)))\n  (#:G12676 (POP #:VALUES-12679)) (#:G12677 (POP #:VALUES-12679)))\n (LET ((#:G12678 (AREF #:G12676 #:G12677)))\n  (PROG1 #:G12678 (INCF #:G12678 1)\n   (SYSTEM::STORE #:G12676 #:G12677 #:G12678)))) ;\nT\n</code></pre>\n\n<p>Now here is a key test case. Here, the place contains a side effect: <code>(aref a (incf i))</code>. This must be evaluated exactly once!</p>\n\n<pre><code>[11]&gt; (macroexpand `(pincf (aref a (incf i))))\n(LET*\n ((#:VALUES-12683 (MULTIPLE-VALUE-LIST (VALUES A (INCF I))))\n  (#:G12680 (POP #:VALUES-12683)) (#:G12681 (POP #:VALUES-12683)))\n (LET ((#:G12682 (AREF #:G12680 #:G12681)))\n  (PROG1 #:G12682 (INCF #:G12682 1)\n   (SYSTEM::STORE #:G12680 #:G12681 #:G12682)))) ;\nT\n</code></pre>\n\n<p>So what happens first is that <code>A</code> and <code>(INCF I)</code> are evaluated, and become the temporary variables <code>#:G12680</code> and <code>#:G12681</code>.  The array is accessed and the value is captured in <code>#:G12682</code>.  Then we have our <code>PROG1</code> which retains that value for return. The value is incremented, and stored back into the array location via CLISP\'s <code>system::store</code> function.  Note that this store call uses the temporary variables, not the original expressions <code>A</code> and <code>I</code>.  <code>(INCF I)</code> appears only once.</p>\n'}, {'answer_id': 36115653, 'author': 'fr_andres', 'author_id': 4511978, 'author_profile': 'https://Stackoverflow.com/users/4511978', 'pm_score': 2, 'selected': False, 'text': '<p>Altough I would definitely keep in mind the remarks and heads-up that <em>simon</em> comments in his post, I really think that <em>user10029</em>\'s approach is still worth a try, so, just for fun, I tried to combine it with the accepted answer to make the <strong>++x</strong> operator work (that is, increment the value of x in 1). Give it a try!</p>\n\n<p><strong>Explanation</strong>: Good old SBCL wouldn\'t compile his version because the \'+\' symbol must be explicitly set on the dispatch-char lookup table with <code>make-dispatch-macro-character</code>, and the macro is still needed to pass over the name of the variable before evaluating it. So this should do the job:</p>\n\n<pre><code>(defmacro increment (variable)\n  "The accepted answer"\n  `(incf ,variable))\n\n(make-dispatch-macro-character #\\+) ; make the dispatcher grab \'+\'\n\n(defun |inc-reader| (stream subchar arg)\n  "sets ++&lt;NUM&gt; as an alias for (incf &lt;NUM&gt;).\n   Example: (setf x 1233.56) =&gt;1233.56\n            ++x =&gt; 1234.56\n            x =&gt; 1234.56"\n   (declare (ignore subchar arg))\n   (list \'increment (read stream t nil t)))\n\n(set-dispatch-macro-character #\\+ #\\+ #\'|inc-reader|)\n</code></pre>\n\n<p>See <code>|inc-reader|</code>\'s <em>docstring</em> for an usage example. The (closely) related documentation can be found here:</p>\n\n<ul>\n<li><a href="http://clhs.lisp.se/Body/f_set__1.htm" rel="nofollow">http://clhs.lisp.se/Body/f_set__1.htm</a> </li>\n<li><a href="http://clhs.lisp.se/Body/f_mk_dis.htm#make-dispatch-macro-character" rel="nofollow">http://clhs.lisp.se/Body/f_mk_dis.htm#make-dispatch-macro-character</a></li>\n</ul>\n\n<p>This implementation has as consequence that number entries like +123 are no longer understood (the debugger jumps in with <code>no dispatch function defined for #\\Newline</code>) but further workaround (or even avoiding) seems reasonable: if you still want to stick with this, maybe the best choice is not to take ++ as prefix, but ## or any other more DSL-ish solution</p>\n\n<p>cheers!</p>\n\n<p>Andres</p>\n'}]
['https://Stackoverflow.com/questions/65607', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1256/']