I have a macro called \logic
which helps me write logical formulas faster by simplifying some common logical symbols. So when I write $\logic{p -> q}$
I obtain $p \to q$
.
Here's the code:
\documentclass{article}
\makeatletter
%
% Command to format a formula with a succinct and natural syntax
%
\usepackage{xparse}
\usepackage{xstring}% for \StrSubstitute
\usepackage{pgffor}% for \foreach
% the strange `\iffalse{\fi` thing is a 'brace hack', to make this work inside
% `tabular`-like envs. See https://tex.stackexchange.com/questions/452442
\NewDocumentCommand\logic{+m}{\iffalse{\fi
\def\gt@formula{#1}%
\saveexpandmode
\saveexploremode
\expandarg
\exploregroups
\foreach \gt@keyword/\gt@operator in \gt@logic@operators {%
\StrSubstitute{\gt@formula}{\gt@keyword}{\gt@operator}[\@temp]%
\global\let\gt@formula\@temp
}%
\restoreexploremode
\restoreexpandmode
\ensuremath{\gt@formula}%
\iffalse}\fi}
\def\gt@logic@operators{}
\NewDocumentCommand\RegisterLogicOperators{m}{
\def\gt@logic@operators{#1}
}
\makeatother
\RegisterLogicOperators{
!/\neg,
&&/\land,
&/\land,
\&/\land,
||/\lor,
|/\lor,
<->/\longleftrigtharrow,
->/\to,
~>/\leadsto,
<-/\impliedby,
<</\llangle,
>>/\rrangle,
<=/\le,
>=/\ge,
==/\equiv,
[[/\llbracket,
]]/\rrbracket,
}
\begin{document}
This is a logic formula: $\logic{((p -> q) & p) -> q}$.
\end{document}
However, the macro is very slow. You don't notice when you use it once, but in a paper with heavy usage the compilation time goes up very quickly. I suppose the bottleneck here is the \StrSubstitute
macro from the xstring
package, which seems a bit overkill for what I have to do, but I do not know how to obtain the same result faster. Also note that the real-world usage has a much longer list of replacements in the call to \RegisterLogicOperators
.
Is there a way to improve the performance of this macro?
\logic
? It would be fairly simple to memoize the results from\logic
in that case.