﻿ 循环 – 在数学中的ForEach循环 - 代码日志

#### 循环 – 在数学中的ForEach循环

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

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

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

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

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

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

Mathematica(6.0)的较新版本通过采用迭代器参数的替代形式，将Do []和Table []的一般化版本几乎完全符合您的要求。例如，

``````Do[
Print[i],
{i, {1, 2, 3}}]
``````

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

``````Attributes[ForEach] = {HoldAll};

ForEach[var_Symbol, list_, expr_] :=
ReleaseHold[
Hold[
Scan[
Block[{var = #},
expr] &,
list]]];

ForEach[vars : {__Symbol}, list_, expr_] :=
ReleaseHold[
Hold[
Scan[
Block[vars,
vars = #;
expr] &,
list]]];
``````

HoldAll []功能允许您组合各种各样的自定义控件结构。 ReleaseHold [Hold […]]通常是组装一堆Mathematica代码以便稍后评估的最简单的方法，Block [{x =#}，…]允许您的表达式主体中的变量绑定到所需的任何值。

``````ForEach[patt_, list_, expr_] :=
ReleaseHold[Hold[
Module[{f},
f[patt] := expr;
Scan[f, list]]]]
``````

``````ForEach[patt_, list_, expr_] :=
With[{bound = list},
ReleaseHold[Hold[
Cases[bound,
patt :> expr];
Null]]]
``````