title: ForEach loop in Mathematica
body: <p>I'd like something like this:</p>
  
  <pre><code>each[i_, {1,2,3},
    Print[i]
  ]
  </code></pre>
  
  <p>Or, more generally, to destructure arbitrary stuff in the list you're looping over, like:</p>
  
  <pre><code>each[{i_, j_}, {{1,10}, {2,20}, {3,30}},
    Print[i*j]
  ]
  </code></pre>
  
  <p>Usually you want to use <code>Map</code> or other purely functional constructs and eschew a non-functional programming style where you use side effects.  But here's an example where I think a for-each construct is supremely useful:  </p>
  
  <p>Say I have a list of options (rules) that pair symbols with expressions, like</p>
  
  <pre><code>attrVals = {a -&gt; 7, b -&gt; 8, c -&gt; 9}
  </code></pre>
  
  <p>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</p>
  
  <pre><code>each[a_ -&gt; v_, attrVals, h[a] = v]
  </code></pre>
  
  <h2>Additional test cases</h2>
  
  <p>In this example, we transform a list of variables:</p>
  
  <pre><code>a = 1;
  b = 2;
  c = 3;
  each[i_, {a,b,c}, i = f[i]]
  </code></pre>
  
  <p>After the above, <code>{a,b,c}</code> should evaluate to <code>{f[1],f[2],f[3]}</code>.  Note that that means the second argument to <code>each</code> should be held unevaluated if it's a list.</p>
  
  <p>If the unevaluated form is not a list, it should evaluate the second argument.  For example:</p>
  
  <pre><code>each[i_, Rest[{a,b,c}], Print[i]]
  </code></pre>
  
  <p>That should print the values of <code>b</code> and <code>c</code>.</p>
  
  <p><strong>Addendum</strong>: To do for-each properly, it should support <code>Break[]</code> and <code>Continue[]</code>.  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 <code>Break[]</code> and <code>Continue[]</code>.</p>
  
  <p>And another problem with the answers so far: they eat <code>Return[]</code>s. That is, if you are using a ForEach loop in a function and want to return from the function from within the loop, you can't.  Issuing Return inside the ForEach loop seems to work like <code>Continue[]</code>. This just (wait for it) threw me for a loop.</p>