[Tex/LaTex] How to write a macro having comma-separated and variable number of arguments

comma-separated listmacrosparsing

I want to write a macro in LaTeX2e that can pass \textcolor, which is embedded in another macro, the values of the colour model gray, rgb, or cmyk. The number of arguments specified implies the colour model to be used; 1 argument for gray, 3 for the rgb, and 4 for the cmyk model. I was able to write a macro that does what I want, but with the arguments in the standard manner in braces. This is the code I was able to write by modifying the answers here.

\makeatletter  
\def\setmycolour#1{%  
\@ifnextchar\bgroup%  
    {\docolour{#1}}  
    {\dogray{#1}}  
}  
\def\dogray#1{This is gray hue #1.}  
\def\docolour#1#2#3{%  
\@ifnextchar\bgroup%  
    {\docmyk{#1}{#2}{#3}}  
    {\dorgb{#1}{#2}{#3}}  
}  
\def\dorgb#1#2#3{This is rgb colour #1,#2,#3.}  
\def\docmyk#1#2#3#4{This is cmyk colour #1,#2,#3,#4.}  
\makeatother

I use the macro as

\setmycolour{0.85}\\
\setmycolour{1}{0}{0}\\
\setmycolour{1}{0}{0}{0}\

I want to use the macro, for example, as \setmycolour{1,0,0} or \setmycolour{0.85}. How do I parse the arguments in the macro definition to do this? Is the above code the best way to get the effect I want?

Best Answer

The comments what color we have is only for demonstration here.

\documentclass{article}
\usepackage[T1]{fontenc}

\makeatletter  
\def\setmycolour#1{\expandafter\setmycolour@i#1,,,,\@nil}
\def\setmycolour@i#1,#2,#3,#4,#5\@nil{% 
  \ifx$#2$ we have gray => #1 \else
    \ifx$#3$ we have a wrong color setting \else
      \ifx $#4$ we have a rgb setting => #1,#2,#3\else
                we have a cmyk setting =>#1,#2,#3,#4
      \fi
    \fi
  \fi 
}  
\makeatother

\begin{document}

\setmycolour{0.5}\par
\setmycolour{0.5,0.6}\par
\setmycolour{0.5,0.6,0.7}\par
\setmycolour{0.5,0.6,0.7,0.8}\par

\end{document}