n回目に使用したときに定義が変わるコマンド

n回目に使用したときに定義が変わるコマンド

最初に呼び出されたときと次に呼び出されたときとで異なる動作をするコマンドが必要です。現在は を使用しています。\newcommand\foo{First\gdef\foo{Next}}つまり、最初に呼び出されたときにコマンド自体が再定義されます。

さらに、ある時点でその意味を「リセット」する必要があるので、 を定義します\newcommand\resetfoo{\gdef\foo{First\gdef\foo{Next}}}

しかし、これは私にとってはかなり難しいようです。これを行う一般的な方法があるかもしれませんが、私はそれを知りません(また、私は拡大)。この種の問題を解決する正しい方法は何ですか?

質問

質問にあるように、もっと一般的な方法が必要です。つまり、定義を変更する関数です。th「拡張」(適切な場所でこの単語を使用しているかどうかわかりません)。この問題をどのように解決しますか?必要な も必要です\resetfoo

まだ何らかの方法で実行されていない場合は、何らかのコマンド\changedefinitionafter\foo{3}{OneTwoThree}{Next}などを用意することを考えています。expl3解決策も歓迎します。

より一般的な MWE を以下に示します。

\documentclass{scrartcl}

\newcommand\foo{First\gdef\foo{Next}}
\newcommand\resetfoo{\gdef\foo{First\gdef\foo{Next}}}

\begin{document}

\foo~\foo~\foo
\resetfoo~\foo~\foo

\end{document}

また、質問のタイトルのタグや提案も歓迎します。

答え1

次の例を見てください。

\documentclass{article}

\newcounter{testcount}

\newcommand{\modifyme}{%
\addtocounter{testcount}{1}
\ifnum\thetestcount<3%
    Hello 
\fi
\ifnum\thetestcount>2%
    World
\fi
}

\newcommand{\resetme}{\setcounter{testcount}{0}}

\begin{document}

\modifyme

\modifyme

\modifyme

\modifyme

\resetme

\modifyme

\end{document}

更新された例

答え2

カウンターを使うのが大好きです! ここでは、指定された数字の後の展開のみが\changedefinitionafter変更されます。

\documentclass{article}
\pagestyle{empty}% for cropping
\makeatletter
\newcount\count@foo
\newcount\nth@foo
\newcommand\changedefinitionafter[4]{
    % #1: name of macro
    % #2: exceptional occurence
    % #3: normal expansion
    % #4: exceptional expansion
    \global\count@foo=0
    \global\nth@foo=#2
    \gdef#1{%
        \advance\count@foo by 1
        \ifnum\count@foo=\nth@foo
            #4%
        \else
            #3%
        \fi
    }
    \edef\resetname{reset\expandafter\@gobble\string#1}
    \expandafter\gdef\csname \resetname \endcsname{\global\count@foo=0 }
}
\makeatother
\begin{document}
\obeylines
\changedefinitionafter\foo{3}{OneTwoThree}{Next}
\foo
\foo
\foo
\foo
\resetfoo
\foo
\foo
\foo
\foo
\end{document}

ここに画像の説明を入力してください

答え3

カウンターはありませんが、このタイプのコマンドごとに 3 つのマクロがあります。

\documentclass{article}

\makeatletter
\newcommand{\newchangingcommand}[4]{%
  % #1 = macro name
  % #2 = steps
  % #3 = value until step #1
  % #4 = value from step #1
  \@namedef{\string#1@counter}{0}%
  \@namedef{\string#1@limit}{#2}%
  \def#1{%
     % step the counter
     \global\@nameedef{\string#1@counter}{\number\numexpr\@nameuse{\string#1@counter}+1\relax}%
     \ifnum\@nameuse{\string#1@counter}=\@nameuse{\string#1@limit}\relax
       \gdef#1{#4}#4%
     \else
       #3%
     \fi
  }%
}
\providecommand\@nameedef[1]{\expandafter\edef\csname#1\endcsname}
\makeatother

\newchangingcommand{\foo}{3}{Two}{Next}
\newchangingcommand{\foob}{2}{One}{Next}

\begin{document}

\foo--\foob\par
\foo--\foob\par
\foo--\foob\par
\foo--\foob\par

\end{document}

ここに画像の説明を入力してください

引数を移動する際にこのようなコマンドを使用すると、いくつかの理由で失敗することに注意してください。

関連情報