15

\FORALL gives a "for all" loop, i would like to redefine it so that it shows "for each" instead. Any way to do that?

By the way, foreach is more often used in real programming languages than forall, is that correct?

4
  • your second question is off topic here. Better off asking it on StackOverflow?
    – Seamus
    May 16, 2011 at 10:43
  • I can't recall seeing a forall statement in any programming language I learned. AFAIK it would require a foreach in its implementation anyway, i.e. foreach VAR in ARRAY { if (somefunc(VAR)) { do_something } }, so it would automatically be more often used. May 16, 2011 at 11:03
  • @Martin: But "for all" often makes more sense in pseudocode than "for each", because pseudocode often operates on sets and it's natural to write "for all x \in Set". May 16, 2011 at 12:19
  • 1
    @Andrey - I prefer "for each x in S" or more commonly "for any x in S" as "for all" indicates plural form as far as I feel.
    – colinfang
    May 16, 2011 at 12:59

4 Answers 4

15

Simple enough and covered in the algorithms manual:

\renewcommand{\algorithmicforall}{\textbf{for each}}

This command redefines the macro that is used to typeset \FORALL. It should be placed in the document preamble.

7
  • 3
    Then I would also say \let\FOREACH\FORALL and use \FOREACH instead in the code. Maybe also change \FORALL to an error message afterwards. This makes the code more readable and avoids confusion. May 16, 2011 at 10:43
  • @Martin Is there anyway I can place \let\FOREACH\FORALL outside the begin{algorithmic} section? I tried \let\FOREACH\algorithmicforall but it didn't work
    – colinfang
    May 16, 2011 at 11:41
  • 2
    @colinfang: I would put the \let\FOREACH\FORALL in the preamble after loading the package. Using \let\FOREACH\algorithmicforall seems to be wrong. May 16, 2011 at 11:50
  • @Martin - if I put it after usepackage, it doesn't work. The only way it works is to add the setting each time the environment invokes.
    – colinfang
    May 16, 2011 at 12:16
  • 1
    @colinfang: I see, then use \def\FOREACH{\FORALL} instead. It is only a cosmetic change anyway. May 16, 2011 at 12:27
12

You can also use the following trick to convert \FOR into \FOREACH in algorithms package

\FOR{\textbf{each} a in b}
\STATE do something
\ENDFOR
4

There is a For Each loop in the algorithm2e package.

1
  • 1
    eh, I have just got used to the algorithms package... is algorithm2e better?
    – colinfang
    May 16, 2011 at 10:24
1

The algorithmicx package lets defined its own commands. In your case you could put in the preamble:

\algblockdefx[Foreach]{Foreach}{EndForeach}[1]{\textbf{foreach} #1 \textbf{do}}{\textbf{end foreach}}

which can then be used as a For loop:

\Foreach{$i \in I$}
    \State bar
    \State foo
\EndForeach

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .