15

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} 

?

simon520
  • 151

2 Answers2

6

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
wipet
  • 74,238
2

@egreg has shown how to compare two fully expanded strings (On testing two fully expanded character strings for equality), and you could apply his technique here.

I have added an error message in case you reuse a symbol.

\documentclass{article}
\usepackage{pdftexcmds}

\newcommand{\symbolI}{A}
\newcommand{\symbolII}{\pi r^2}
\newcommand{\symbolIII}{\pi r^2}

\makeatletter
\newcommand{\TestSameSymbols}[2]{%
    \ifnum\pdf@strcmp{#1}{#2}=\z@ 
        \typeout{%
            ERROR: \noexpand#2 (#2) is the same as \noexpand#1.%
        }
    \fi%
}
\makeatother

\begin{document}

\TestSameSymbols{\symbolI}{\symbolII}
\TestSameSymbols{\symbolII}{\symbolIII}

\[ \symbolI = \symbolII \]

\end{document}
musarithmia
  • 12,463