¿Macro expandible con bucles y funciones de cadena avanzadas?

¿Macro expandible con bucles y funciones de cadena avanzadas?

Este podría ser un problema muy básico (como seguimiento deesta pregunta) pero no sé cómo hacerlo: necesito una macro \mycmd{sometext}que produzca una cadena dependiendo del primer carácter de su argumento. Esta cadena resultante luego debe escribirse en mayúscula con \makefirstuc.

\documentclass{article}
\usepackage{xparse}  % used in example below
\usepackage{pgffor}  % used in example below
\usepackage{xstring} % used in example below

\newcommand{\mycmd}[1]{
  % here, I define a list of letters {a,e,i,o,u,A,E,I,O,U}
  % that will lead to the output "an " in case
  % the argument string starts by one of them.
  % Otherwise the output shall be "a ".
}

\begin{document}
  \mycmd{somestring}                % should print "a "
  \makefirstuc{\mycmd{sometext}}    % should print "A "
  \mycmd{otherstring}               % should print "an "
  \makefirstuc{\mycmd{otherstring}} % should print "An "
\end{document}

Intenté realizar esto usando el pfgforpaquete para el bucle y comparando el primer carácter con \IfBeginWithel del xstringpaquete. Sin embargo, esto aparentemente conduce a comandos no expandibles, por lo que \makefirstucfalla.¿Cómo se puede lograr un comando ampliable con esta funcionalidad?

Hasta ahora creé el siguiente comando no expandible:

\NewDocumentCommand{\mycmd}{m}{%
  \def\undefart{a\space}%
  \foreach \c in {a,e,i,o,u,A,E,I,O,U}{%
    \IfBeginWith{#1}{\c}{\global\def\undefart{an\space}}{}%
  }%
  \undefart%
}

Respuesta1

Esto es bastante fácil de usar expl3(hay varios enfoques posibles):

\documentclass{article}
\usepackage{expl3,xparse}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand \mycmd { m }
  {
    \__mycmd_loop:nN {#1} aeiouAEIOU \q_recursion_tail \q_recursion_stop
  }
\cs_new:Npn \__mycmd_loop:nN #1#2
  {
    \quark_if_recursion_tail_stop_do:nn {#2} { a }
    \tl_if_head_eq_charcode:nNT {#1} #2
      {
        \use_i_delimit_by_q_recursion_stop:nw { an }
      }
    \__mycmd_loop:nN {#1}
  }
\ExplSyntaxOff
\usepackage{mfirstuc}
\begin{document}

  \mycmd{somestring}                % should print "a "
  \emakefirstuc{\mycmd{sometext}}    % should print "A "
  \mycmd{otherstring}               % should print "an "
  \emakefirstuc{\mycmd{otherstring}} % should print "An "
\end{document}

Como \makefirstucno hay expansión, he tenido que usar la eversión. Probablemente preferiría evitar eso usando el expandible (y compatible con Unicode) \text_titlecase:n:

\documentclass{article}
\usepackage{expl3,xparse}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand \mycmd { m }
  {
    \__mycmd_loop:nN {#1} aeiouAEIOU \q_recursion_tail \q_recursion_stop
  }
\cs_new:Npn \__mycmd_loop:nN #1#2
  {
    \quark_if_recursion_tail_stop_do:nn {#2} { a }
    \tl_if_head_eq_charcode:nNT {#1} #2
      {
        \use_i_delimit_by_q_recursion_stop:nw { an }
      }
    \__mycmd_loop:nN {#1}
  }
\cs_new_eq:NN \Mymakefirstuc \text_uppercase:n
\ExplSyntaxOff
\begin{document}

  \mycmd{somestring}                % should print "a "
  \Mymakefirstuc{\mycmd{sometext}}    % should print "A "
  \mycmd{otherstring}               % should print "an "
  \Mymakefirstuc{\mycmd{otherstring}} % should print "An "
\end{document}

Dependiendo del número de casos, podría ser conveniente poner primero en minúsculas todas las entradas

\DeclareExpandableDocumentCommand \mycmd { m }
  {
    \exp_args:Nf \__mycmd:n { \text_lowercase:n {#1} }
  }
\cs_new:Npn \__mycmd:n #1
  {
    \__mycmd_loop:nN {#1} aeiou \q_recursion_tail \q_recursion_stop
  }

Respuesta2

He aquí un enfoque conexpl3

\documentclass{article}
\usepackage{xparse,glossaries}

\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\indef}{m}
 {
  \str_case_x:nnF { \tl_head:f { \tl_lower_case:n { #1 } } }
   {
    {a}{an}
    {e}{an}
    {i}{an}
    {o}{an}
    {u}{an}
  }
  {a}~#1
 }
\ExplSyntaxOff

\begin{document}

\indef{abc} --- \indef{cde} --- \indef{ABC} --- \indef{CDE}

\emakefirstuc{\indef{abc}} --- \emakefirstuc{\indef{cde}} ---
\emakefirstuc{\indef{ABC}} --- \emakefirstuc{\indef{CDE}}

\end{document}

ingrese la descripción de la imagen aquí

Respuesta3

Aquí hay una solución basada en LuaLaTeX. Define dos macros "contenedores" totalmente expandibles denominadas \mycmdy \mkfirstuc, que pasan sus argumentos a funciones Lua denominadas mycmdy mkfirstuc. Las funciones de Lua realizan el trabajo real de anteponer "an" o "a" a una cadena y de poner en mayúsculas el primer carácter de la cadena, respectivamente.

ingrese la descripción de la imagen aquí

% !TEX TS-program = lualatex
\documentclass{article}

%% Lua-side code
\usepackage{luacode}
\begin{luacode}
function mycmd ( s )
  if string.match ( string.sub(s,1,1) , "[aeiouAEIOU]" ) then
    return tex.sprint ("an " .. s)
  else
    return tex.sprint ("a " .. s)
  end
end
function mkfirstuc ( s )
  return tex.sprint ( string.upper(string.sub(s,1,1)) .. string.sub(s,2) )
end
\end{luacode}

%% TeX-side code
\newcommand\mycmd[1]{\directlua{mycmd(\luastring{#1})}}
\newcommand\mkfirstuc[1]{\directlua{mkfirstuc(\luastring{#1})}}

\begin{document}
\mycmd{abc}, \mycmd{def}, \mycmd{ABC}, \mycmd{DEF}.

\mkfirstuc{\mycmd{abc}}, \mkfirstuc{\mycmd{def}}, 
\mkfirstuc{\mycmd{ABC}}, \mkfirstuc{\mycmd{DEF}}. 
\end{document}

Respuesta4

¿Es esto lo que se quiere decir? No es el uso más efectivo de expl3, lo sé ;-)

\documentclass{article}
\usepackage{xparse}  % used in example below
\usepackage{pgffor}  % used in example below
\usepackage{xstring} % used in example below

\ExplSyntaxOn

\clist_set:Nn \l_tinytot_lowercaseletters_clist {a,e,i,o,u}
\clist_set:Nn \l_tinytot_letters_clist {a,e,i,o,u,A,E,I,O,U}

\NewDocumentCommand{\makefirstuc}{m}{%
  \tl_to_uppercase:n {#1}
}

\NewDocumentCommand{\checkstart}{m}{%
  \tl_set:Nx \l_tmpa_tl {#1}
  \tl_trim_spaces:N \l_tmpa_tl
  \tl_set:Nx \l_tmpb_tl { \tl_item:Nn \l_tmpa_tl {1}}
  \clist_if_in:NVTF \l_tinytot_letters_clist {\l_tmpb_tl }{%
    \clist_if_in:NVTF \l_tinytot_lowercaseletters_clist {\l_tmpb_tl}
    {
      an
    }{
      An
    }
  }{
    \clist_if_in:NVTF \l_tinytot_lowercaseletters_clist {\l_tmpb_tl}
    {
      a
    }{
      A
    }
  }
}  
\ExplSyntaxOff

\newcommand{\mycmd}[1]{%
  \checkstart{#1}
  % here, I define a list of letters {a,e,i,o,u,A,E,I,O,U}
  % that will lead to the output "an " in case
  % the argument string starts by one of them.
  % Otherwise the output shall be "a ".
}

\begin{document}
\mycmd{somestring}                % should print "a "
\makefirstuc{\mycmd{sometext}}    % should print "A "
\mycmd{otherstring}               % should print "an "
\makefirstuc{\mycmd{otherstring}} % should print "An "
\end{document}

información relacionada