Many languages have a Do While loop, how can I do one in Mathematica ?
Asked
Active
Viewed 1,854 times
3
-
Reminds me... – J. M.'s missing motivation Nov 14 '15 at 13:12
-
@J.M. Mr. Wizard deleted it... http://mathematica.stackexchange.com/q/44224/5478 – Kuba Nov 14 '15 at 13:15
-
@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.) – J. M.'s missing motivation Nov 14 '15 at 13:24
-
@J.M. can't vote to undelete, it was deleted by moderator. – Kuba Nov 14 '15 at 13:26
-
Alright I set this one as a dupe. If anyone thinks the other thread should be reopened, cast your vote. – J. M.'s missing motivation Nov 14 '15 at 13:29
2 Answers
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