Many languages have a Do While loop, how can I do one in Mathematica ?
-
$\begingroup$ Reminds me... $\endgroup$– J. M.'s persistent exhaustion ♦Nov 14, 2015 at 13:12
-
$\begingroup$ @J.M. Mr. Wizard deleted it... mathematica.stackexchange.com/q/44224/5478 $\endgroup$– Kuba ♦Nov 14, 2015 at 13:15
-
$\begingroup$ @Kuba, hmm, I'd vote to undelete if my powers weren't unilateral. Why not cast an undelete vote, and hope others do so as well? (That will have the unfortunate effect of making this a dupe, tho.) $\endgroup$– J. M.'s persistent exhaustion ♦Nov 14, 2015 at 13:24
-
$\begingroup$ @J.M. can't vote to undelete, it was deleted by moderator. $\endgroup$– Kuba ♦Nov 14, 2015 at 13:26
-
$\begingroup$ Alright I set this one as a dupe. If anyone thinks the other thread should be reopened, cast your vote. $\endgroup$– J. M.'s persistent exhaustion ♦Nov 14, 2015 at 13:29
2 Answers
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".
-
$\begingroup$ 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. $\endgroup$– faysouNov 14, 2015 at 13:10
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*)