# How can I define a ForEach loop on the basis of the existing ForAll loop?

Is there a way to define new command in algpseudocode based on existing one? In particular, in my document I need to use both \ForAll and \ForEach commands. It turns out that just renaming \ForAll doesn't work for me. I would like to define a new command \ForEach in such a way that it keeps all the functionalities of \ForAll (including typesetting "do" and "end for", and indenting all states inside the loop).

The code below shows what I've tried so far, but obviously that's not the way to go. I need lines 3,4,5 to be shifted together with the new command, and "end for" to be typeset.

\documentclass{article}      % Specifies the document class

\usepackage{amsmath}
\usepackage{algpseudocode}
\usepackage{algorithm}

\algnewcommand\algorithmicforeach{\textbf{for each:}}
\algnewcommand\ForEach{\item[ \algorithmicforeach]}

\begin{document}

\begin{algorithm} \caption{Iterative Policy Evaluation Algorithm}
\begin{algorithmic}[1]
\Require $\pi$, the policy to be evaluated
\State Initilize $V(s) = 0$, for all $s \in \mathcal S^+$
\Repeat
\ForEach {$s \in \mathcal S$}
\State $v \gets V(s)$
\State $V(s) \gets \sum_a \pi(s,a) \sum_{s'} \mathcal P_{ss'}^a [ \mathcal R_{ss'}^a + \gamma V(s')$
\State $\Delta \gets \max(\Delta, |v- V(s)|)$
%\EndFor
\Until {$\Delta < \theta \text{ (a small positive number)}$}
\Ensure $V \approx V^\pi$
\end{algorithmic}
\end{algorithm}

\end{document}


In the algpseudocode package, the ForAll loop is defined as follows:

\algnewcommand\algorithmicforall{\textbf{for all}}
\algdef{S}[FOR]{ForAll}[1]{\algorithmicforeall\ #1\ \algorithmicdo}


You can simply define a ForEach loop that mimicks a ForAll one as follows:

\algnewcommand\algorithmicforeach{\textbf{for each}}
\algdef{S}[FOR]{ForEach}[1]{\algorithmicforeach\ #1\ \algorithmicdo}


\documentclass{article}      % Specifies the document class

\usepackage{amsmath}
\usepackage{algpseudocode}
\usepackage{algorithm}

\algnewcommand\algorithmicforeach{\textbf{for each}}
\algdef{S}[FOR]{ForEach}[1]{\algorithmicforeach\ #1\ \algorithmicdo}

\begin{document}

\begin{algorithm} \caption{Iterative Policy Evaluation Algorithm}
\begin{algorithmic}[1]
\Require $\pi$, the policy to be evaluated
\State Initilize $V(s) = 0$, for all $s \in \mathcal S^+$
\Repeat
\ForEach {$s \in \mathcal S$}
\State $v \gets V(s)$
\State $V(s) \gets \sum_a \pi(s,a) \sum_{s'} \mathcal P_{ss'}^a [ \mathcal R_{ss'}^a + \gamma V(s')$
\State $\Delta \gets \max(\Delta, |v- V(s)|)$
\EndFor
\Until {$\Delta < \theta \text{ (a small positive number)}$}
\Ensure $V \approx V^\pi$
\end{algorithmic}
\end{algorithm}

\end{document}