[Tex/LaTex] Assertions in Latex

best practicesmacrostex-core

I am writing a long latex document and use many macros for defining mathematical symbols. I would like to ensure that there is no clash in the notation. For example, something like

\newcommand{\symbolone}{A}
\newcommand{\symboltwo}{A}

should not happen. Is there something like an assertion in latex such that I can do

\assert{\symbolone != \symboltwo} 

?

Best Answer

My solution introduces the macro \singledef which defines control sequence (like \def) but provides two more features:

  • it checks if the control sequence is defined. If yes, then error message is printed and the control sequence keeps its original meaning.
  • it saves the name of defined control sequence into the \singledeflist internal macro. When the next control sequence is defined via \singledef then it is defined but it is checked if the same control sequence (equivalent via \ifx) was defined and saved in \singledeflist. If yes, then error message is printed and the new control sequence is kept undefined.

The code:

\def\singledeflist{}

\def\singledef#1{% 
   \ifx#1\undefined
      \def\next{\singledefA#1}%
      \afterassignment\next
      \expandafter\def\expandafter#1%
   \else
      \errmessage{The \string#1 is defined already}% 
      \expandafter\def\expandafter\tmp
   \fi
}
\def\singledefA#1{\def\next{\singledefB#1}\expandafter\next\singledeflist\end}
\def\singledefB#1#2{%
   \ifx#2\end
      \expandafter\def\expandafter\singledeflist\expandafter{\singledeflist#1}% 
   \else
      \ifx#1#2%
         \errmessage{The \string#1 is the same as \string#2}%
         \let#1=\undefined
         \singledefC
      \fi
      \expandafter\next
   \fi
}  
\def\singledefC#1\end{\fi\fi}

\singledef\A{aha}  % this is like \def\A{aha}
\singledef\B{bha}  % this is like \def\B{bha}
\singledef\C{bha}  % this prints the error: The \C is the same as \B