Somewhat inspired by How to automatically draw tree diagram of prime factorization with LaTeX? and mostly motivated by laziness, I'd like to be able to draw a tree defined by LISP syntax for a class I'll be TA'ing next semester.
For those who don't know, LISP is a programming language (the second oldest, in fact) that specifies programs directly as trees:
(defun count (a l &optional c)
(if l ;; if l is not empty [()===nil]
(count a ;; return the number of a's in the cdr
(cdr l)
(+ (if c c 0) ;; add c (if it wasn't given, start with 0)
(if (equal a (car l)) 1 0))) ;; and 1 or 0, if a==l[0]
c)) ;; otherwise, return the count
Given the (if ...) sequence, I'd like it to come up with something like this:
\documentclass{article}
\usepackage{tikz}
\usepackage[active,tightpage]{preview}
\PreviewEnvironment{tikzpicture}
\setlength{\PreviewBorder}{10pt}%
\usetikzlibrary{arrows}
\begin{document}
\begin{tikzpicture}[->,>=stealth',level/.style={sibling distance = 10cm/#1,
level distance = 1.5cm}]
\node {if}
child{ node {l} }
child{ node {count}
child{ node {a} }
child{ node {cdr}
child{node {l}}}
child{ node {+}
child{ node {if}
child { node {c} }
child { node {c} }
child { node {0} }}
child{ node {if}
child { node {equal}
child {node {a}}
child {node {car}
child { node {l}}}}
child { node {1}}
child { node {0}}}}}
;
\end{tikzpicture}
\end{document}
Obviously the style is whatever looks best, but I'd like the macro to avoid the crossings that my example is a victim of.

My best guesses are to make ( and ) active somehow, but I don't have the TeXnical experience to define such macros off-hand.



forestrequires terminals to be bracketed, which is the problem. Hmm. Back to the drawing board, I guess. – Alan Munn Oct 26 '13 at 19:13forest-qtreedoesn't solve the problem I think, since it also deals with the.in the label thatqtreeexpects. – Alan Munn Oct 26 '13 at 19:47forest-qtreecan be used when we include the.if it is not there. See my answer. – Qrrbrbirlbel Oct 26 '13 at 20:16forest-qtreecode. :) – Alan Munn Oct 26 '13 at 20:34