# Problem with implementing \ifcsname … \endcsname into a custom macro

I apologise in advance if this is a bad question but I have been trying to read up macros in Latex with the TeX-book but I just cannot work out why this doesn't work.

So I have a 'working' macro (pasted below) which lets you wrap \ans{<answer>} around answers in a tutorial sheet to save the answer to an 'array' of sorts; the answers in the array are then used to create an answer sheet with the command \s. 'Working' macro code:

        \titleformat{\section}{\titlerule\vspace{1mm}\normalfont\secfnt\bfseries}{\thesection}{2em}{}
\renewcommand{\thesection}{{\noindent\hrulefill}\\ Problem \arabic{section}.}
%%%%%%%Each problem label generated with \section{}

\newcounter{Questionpart}[section]
\newcommand{\Qpart}{(\stepcounter{Questionpart}\alph{Questionpart})
\global\expandafter\def\csname Prob\the\value{section}\endcsname{\the\value{Questionpart}}
}
%%%An attempt to count the parts in each problem but \csname Prob<number> \endcsname doesnt work with \foreach \y in {1,...,\csname Prob<number> \endcsname}
%%%%%Parts a),b).....e), generated by \Qpart.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%Command of interest%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\long\def\ans#1{
#1
}%An 'array' structure which names each element as ans<problem_number><problem_part_in_numbers>

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand{\p}[1]{
\csname ans#1 \endcsname
}%lets \s call the elements in the 'array'

\newcommand{\s}{\newpage
\begin{center}
\Large\textbf{Solutions}
\end{center}
\foreach \x in {1,...,\value{section}}
{
\textbf{Problem \x}\par
\begin{enumerate}[label=(\alph*)]
\foreach \y in {1,...,10}
%couln't count the parts in a problem so set to 10 as a general size.
{\p{\x\y}\par
}
\end{enumerate}
}
}


ISSUE:

I would like to implement a concatenate feature to the \ans{} command so that each \ans{} in the same Problem part will add together to create a full answer. (sometimes it may be a 'prove that' question and the key points are spread out)

I tried something like this (which didn't work):

\makeatletter
\long\def\ans#1{% if \DP@#1 is defined append to it otherwise create it
\if\csname ans\the\value{section}\endcsname
\edef\DP@tmp{\csname ans\the\value{section}\endcsname,#1}%
\else
\edef\DP@tmp{#1}%
\fi
\global\expandafter\let\csname ans\the\value{section}\endcsname\DP@tmp
#1
}
\makeatother


I will greatly appreciate help or any pointers.

• \if\csname and \ifcsname are very different! – egreg Oct 3 at 11:20
• \if\csname ans\the\value{section}\endcsname compares the first two characters in the expansion of the macro you might write informally as \ans1 and is true if they are the same. – David Carlisle Oct 3 at 11:43