Just a few remarks here... You should definitely take a look at the different varieties of Map
in the Documentation, and there's also ParallelMap
since you mentioned parallelization. Other functions also have parallel versions, like ParallelDo
.
Also, I know you said that speed isn't your primary concern, but just in case you're interested... Here's a Stackexchange question on the topic (item 1.4 in the accepted answer briefly addresses loop constructs), and then here's a Wolfram Blog post on the topic in the same general direction.
I realize that a lot of Mathematica users are allergic to loop constructs, and I know that seems strange (borderline infuriating) to anyone who is used to other programming languages. Ideology aside, the core of that allergy is that there are so many different approaches available that you can solve a given problem in a variety of ways. That means you can usually find a solution where the code has the same structure as the problem itself. Now we all know there's no guarantee that that would be the most efficient implementation, but it's certainly the one that's fastest to write. Sometimes your problem really is a loop, but maybe it's more like a matrix multiplication or a rearranging of lists or strings, and it just seems unnecessary to re-formulate the problem into a loop structure. On top of that, Frank is also right: for many problems that are not "naturally" loops, other approaches are a lot faster because they're already optimized inside of specialized functions, or because Table
will be able to compile or pack something behind the scenes when Do
for some reason can't. And here's the bad news: Actually optimizing computation time can be a tiresome excercise in Mathematica because it's not straight-forward and it's not immediately clear whether a noticable speed-up is possible or not. The two sources linked above will give you an idea and a list of things to consider. If you want a rule of thumb: "Use the highest-level built-in meta-function possible" tends to be good advice, and short code has decent odds of being fast code. (Take that with a huge grain of salt.)
By the way, for your test, you use test=true
and test=false
. If you wanted the Boolean true and false, you'll have to use True
and False
(all built-in symbols in Mathematica are capitalized). Your code very likely still works because you essentially use new undefined variables true
and false
and symbolically compare them with test
.