ForEach loop in Mathematica.

Posted by dreeves on Stack Overflow See other posts from Stack Overflow or by dreeves
Published on 2008-10-01T23:25:43Z Indexed on 2011/01/16 2:53 UTC
Read the original article Hit count: 163

Filed under:
|

I'd like something like this:

ForEach[i_, {1,2,3},
  Print[i]
]

Or, more generally, to destructure arbitrary stuff in the list you're looping over, like:

ForEach[{i_, j_}, {{1,10}, {2,20}, {3,30}},
  Print[i*j]
]

(Meta-question: is that a good way to call a ForEach loop, with the first argument a pattern like that?)

ADDED: Some answerers have rightly pointed out that usually you want to use Map or other purely functional constructs and eschew a non-functional programming style where you use side effects. I agree! But here's an example where I think this ForEach construct is supremely useful:

Say I have a list of options (rules) that pair symbols with expressions, like

attrVals = {a -> 7, b -> 8, c -> 9}

Now I want to make a hash table where I do the obvious mapping of those symbols to those numbers. I don't think there's a cleaner way to do that than

ForEach[a_ -> v_, attrVals, h[a] = v]

ADDED: I just realized that to do ForEach properly, it should support Break[] and Continue[]. I'm not sure how to implement that. Perhaps it will need to somehow be implemented in terms of For, While, or Do since those are the only loop constructs that support Break[] and Continue[]. If anyone interested in this wants to ask about that as a separate question, please do!

© Stack Overflow or respective owner

Related posts about loops

Related posts about mathematica