
如果 Latex3 中滿足某些條件,如何停止函數運行其餘程式碼?
現在我必須建立嵌套條件並複製幾個預設情況。如果預設情況相當大,程式碼可讀性就會變差。
\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
這是我想要的程式語言
function(arg){
if(condition 1){
return <first case>;
}
if(condition 2){
return <second case>;
}
return <default case>;
}
答案1
有幾種方法可以實現這一目標。我可能會使用基於謂詞的方法和惰性求值:
\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
對於更複雜的情況,我通常會將“有效負載”(動作)放入輔助設備中。
如果您習慣於「返回」格式,則需要一些結束標記標記
\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}
但老實說,我會堅持使用謂詞和適當的助詞。