3

Many languages have a Do While loop, how can I do one in Mathematica ?

faysou
  • 10,999
  • 3
  • 50
  • 125

2 Answers2

5

This can be done much easier by putting the body of the loop into the test, like so:

While[body;test]

For example:

While[False,Print["Evaluated body"]]

gives no output, whereas

While[Print["Evaluated body"];False]
(* Evaluated body *)

does.

PS: The documentation for While presents my approach as the first example under "Scope" and @faysou's approach under "Generalizations and extensions".

LLlAMnYP
  • 11,486
  • 26
  • 65
  • Nice, I didn't know this approach. I wrote another function as it makes it easier for me to explicitely see a DoWhile as an abstraction of a concept, plus I think it's a neat and simple illustration of metaprogramming. – faysou Nov 14 '15 at 13:10
3

Using some basic meta programming it's possible to do it.

SetAttributes[DoWhile,HoldAll];
DoWhile[expr_,condition_]:=
    While[True,
        expr;

        If[! condition,
            Break[];
        ];
    ];

For example

i=0
DoWhile[i++,i<0] (*i=1*)

i=-2
DoWhile[i++,i<0] (*i=0*)
faysou
  • 10,999
  • 3
  • 50
  • 125