Ask HN: Have you ever needed to invert a binary tree at work?
How about we do that in Lisp, and then apply the invert function to its own source code?<p><pre><code>  1&gt; (defun invert (tree)
       (if (atom tree)
         tree
         (cons (invert (cdr tree)) (invert (car tree)))))
  invert
  2&gt; (invert &#x27;(defun invert (tree)
       (if (atom tree)
         tree
         (cons (invert (cdr tree)) (invert (car tree))))))
  ((((nil (((nil ((nil (nil (nil . tree) . car) . invert) (nil (nil . tree) . cdr) . invert) . cons) . tree)
           (nil . tree) . atom) . if)
     nil . tree) . invert) . defun)
</code></pre>
A Lisp tree structure can be regarded not as a binary tree, but as an n-ary tree; under which we can come up with a different semantics for inverting:<p><pre><code>  3&gt; (defun invert2 (tree)
       (if (listp tree)
          [mapcar invert2 (reverse tree)]
          tree))
  invert2
</code></pre>
Now for comparison, we apply that to the original invert:<p><pre><code>  4&gt; (invert2 &#x27;(defun invert (tree)
       (if (atom tree)
         tree
         (cons (invert (cdr tree)) (invert (car tree))))))
  (((((tree car) invert) ((tree cdr) invert) cons) tree (tree atom)
    if)
   (tree) invert defun)
</code></pre>
That&#x27;s actually halfway readable.<p>Okay, now let&#x27;s crank up the stupid knob to about 7.5.<p><pre><code>  5&gt; (defun invert3 (tree)
        (cond ((listp tree)
               [mapcar invert3 (reverse tree)])
              ((symbolp tree) (intern (reverse (symbol-name tree))))
              (t tree)))
        
  invert3
  6&gt; (invert3 &#x27;(defun invert (tree)
       (if (atom tree)
         tree
         (cons (invert (cdr tree)) (invert (car tree))))))
  (((((eert rac) trevni) ((eert rdc) trevni) snoc) eert (eert mota)
    fi)
   (eert) trevni nufed)
</code></pre>
and finally to 11:<p><pre><code>  12&gt; (defun invert4 (tree)
        (let ((tree-picture (with-out-strlist-stream (s)
                              (print tree s))))
          (each ((line tree-picture))
            (let* ((rl (reverse line))
                   (sb (mapcar (relate &quot;()&quot; &quot;)(&quot;) rl)))
              (put-line `@{sb -78}`)))))
  invert4
  13&gt; (invert4 &#x27;(defun invert (tree)
       (if (atom tree)
         tree
         (cons (invert (cdr tree)) (invert (car tree))))))
                                                                   trevni nufed)
                                                        (eert mota) fi) (eert)  
                                       ((eert rdc) trevni) snoc) eert           
                                    (((((eert rac) trevni)                      
  nil
</code></pre>
Look, text-wise left-right mirror image of the printed version of the tree!