2

Does anyone know an easy way to check if an item is a member in a comma-separated list?

Something like this would be excellent:

\ifmember{elem1}{elem1,elem2,elem3}{true}{false}

The above would expand to true since elem1 is in the list.

Thanks

4

2 Answers 2

7

LaTeX has such a test built in already, so you just need to define your requested syntax:

\documentclass{article}

\makeatletter
\newcommand\ifmember[2]{%
\in@{#1}{#2}%
\ifin@
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
}
\makeatother

\begin{document}


\ifmember{elem1}{elem1,elem2,elem3}{true}{false}

\ifmember{elem4}{elem1,elem2,elem3}{true}{false}

\end{document}
1
  • 2
    actually The question is a duplicate (and Heiko's answer there covers this) I'll vote to close. Jan 11, 2016 at 15:53
1

Here's a quick expl3 (well, xparse method, for checking whether the second argument is in the list. However, the clist-variable would be in a command macro, usually,otherwise you would know if it is in the list.

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\IsMember}{mm+m+m}{%
  \clist_set:Nx \l_tmpa_clist {#1}
  \clist_if_in:NnTF \l_tmpa_clist {#2} {#3} {#4}
}
\ExplSyntaxOff


\newcommand{\foo}{%
  elem1,elem2,elem3%
}
\begin{document}
\IsMember{\foo}{elem1}{true}{false}

\IsMember{\foo}{elem5}{true}{false}
\end{document}

Not the answer you're looking for? Browse other questions tagged .