3
$\begingroup$

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

$\endgroup$
5
  • $\begingroup$ Reminds me... $\endgroup$ 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$ 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$ Nov 14, 2015 at 13:29

2 Answers 2

5
$\begingroup$

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".

$\endgroup$
1
  • $\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$
    – faysou
    Nov 14, 2015 at 13:10
3
$\begingroup$

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*)
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.