Function return — expl3

expl3latex3

How can I stop function from running rest of the code if some conditions are met in latex3?

Now I have to build nested conditions and have a couple of default cases duplicated. Code readability gets worse if the default case is quite huge.

\ExplSyntaxOn
\cs_set:Npn \my_func #1 {
    \token_if_cs:NTF #1 {
        \str_eq:nnTF {#1} {\\} {
            first case
        }{
            \token_if_expandable:NTF #1 {
                second case
            }{
                default
            }
        }
    }{
        default
    }
}

\my_func{\\}
\ExplSyntaxOff

Here's what I'd like to have in terms of programming language

function(arg){
    if(condition 1){
        return <first case>;
    }
    if(condition 2){
        return <second case>;
    }

    return <default case>;
}

Best Answer

There are a few ways to achieve this. I'd likely use a predicate-based approach and lazy evaluation:

\ExplSyntaxOn
\cs_set:Npn \my_func:N #1
  {
    \bool_lazy_and:nnTF
      { \token_if_cs_p:N #1 }
      { \token_if_expandable_p:N #1 }
      {
        \str_if_eq:nnTF {#1} { \\ }
          { first case }
          { second case }
      }
      { default }
  }

\my_func:N { \\ }
\ExplSyntaxOff

For more complex cases, I would usually put the 'payload' (actions) into auxiliaries.


If you are wedded to the 'return' format, you need some end marker token

\cs_set:Npn \my_func:N #1
  {
    \token_if_cs:NF #1
      { \__my_func_return:nw { not-a-cs } }
    \token_if_expandable:NF #1
      { \__my_func_return:nw { not-expandable } }
    \__my_func_return:nw { default }
    \__my_func_end:
  }
\cs_new_eq:NN \__my_func_end: \prg_do_nothing:
\cs_new:Npn \__my_func_return:nw #1#2 \__my_func_end:
  {#1}

but honestly I would stick to predicates and appropriate auxiliaries.

Related Question