Mathematica中的ForEach循环 [英] ForEach loop in Mathematica

查看:127
本文介绍了Mathematica中的ForEach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要这样的东西:

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

或更笼统地说,是在您要遍历的列表中破坏任意内容,例如:

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

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

通常,您想使用Map或其他纯函数式构造,并避免使用副作用的非函数式编程风格.但是,在以下示例中,我认为for-each构造极其有用:

Usually you want to use Map 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:

说我有一个将符号与表达式配对的选项(规则)列表,例如

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

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

其他测试用例

在此示例中,我们转换变量列表:

Additional test cases

In this example, we transform a list of variables:

a = 1;
b = 2;
c = 3;
each[i_, {a,b,c}, i = f[i]]

在完成上述操作后,{a,b,c}应评估为{f[1],f[2],f[3]}.请注意,这意味着each的第二个参数(如果是列表)应保持未评估状态.

After the above, {a,b,c} should evaluate to {f[1],f[2],f[3]}. Note that that means the second argument to each should be held unevaluated if it's a list.

如果未评估形式不是列表,则应评估第二个参数.例如:

If the unevaluated form is not a list, it should evaluate the second argument. For example:

each[i_, Rest[{a,b,c}], Print[i]]

应该打印bc的值.

附录:要正确执行每一项,它应支持Break[]Continue[].我不确定如何实现.也许需要以For,While或Do的方式来实现它,因为这是唯一支持Break[]Continue[]的循环构造.

Addendum: To do for-each 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[].

到目前为止,答案的另一个问题是:他们吃了Return[] s.也就是说,如果您在函数中使用ForEach循环,并希望从循环内从该函数返回,则不能这样做.在ForEach循环内发出Return似乎像Continue[]一样工作.只是(等待它)让我循环.

And another problem with the answers so far: they eat Return[]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 Continue[]. This just (wait for it) threw me for a loop.

推荐答案

感谢 Pillsy Leonid Shifrin ,这是我现在正在使用的:

Thanks to Pillsy and Leonid Shifrin, here's what I'm now using:

SetAttributes[each, HoldAll];               (* each[pattern, list, body]      *)
each[pat_, lst_List, bod_] :=               (*  converts pattern to body for  *)
  (Cases[Unevaluated@lst, pat:>bod]; Null); (*   each element of list.        *)
each[p_, l_, b_] := (Cases[l, p:>b]; Null); (* (Break/Continue not supported) *)

这篇关于Mathematica中的ForEach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆