请求代码审查和改进建议(是:制作功能列表的问题)

时间:2011-06-11 10:25:59

标签: wolfram-mathematica

按照acl的要求清理问题:

我有以下代码

AddGeometry[scg_, tfg_, geo_] := 

Module[{
i,
georec},

If[StringQ[geo[[2,1]]]&&StringMatchQ[geo[[2,1]],"GE"],   (* DIRTY, BWAH *)
    AddAsChild[scg, tfg, geo],
    (
    i=1;
    While[i<=Length[geo],
        georec=geo[[i]];
        AddGeometry[scg, tfg, georec];
        i++
    ]
    )
]

SetAttributes[AddGeometry, HoldAll];

geo_看起来像这样:

{
{4, {"GE", {"CU", {{0, 0, 0}, 4}}}, 5, 2}, 
{7, {"GE", {"CU", {{0, 3, 0}, 1}}}, 5, 2},
{12, {"GE", {"CU", {{0, 5, 0}, 2}}}, 5, 2},
}

它包含1,2,... n类型的记录     {4,{“GE”,{“CU”,{{0,0,0},4}}},5,2}

调用代码看起来像

c1 = NewCube[]

(c1得到的值类似于{4,{“GE”,{“CU”,{{0,0,0},4}}},5,2}等。

AddGeometry[scg, tfg, c1]

当需要添加多个几何时:或

AddGeometry[scg, tfg, {c1, c2, c3}]

上面的代码可以使用。

问题:

  • 是否有更简洁的方法(使用多态)来实现它?

来自@acl:

AddGeometry[scg_, tfg_, geo_] := 
Module[{
    georec=geo}, 

    AddAsChild[scg, tfg, georec]

] /; MatchQ[geo, {_, {"GE", __}, __}];      

AddGeometry[scg_, tfg_, geo_] := 
Module[{},
    Map[AddGeometry[scg, tfg, #] & ,geo]
]

2 个答案:

答案 0 :(得分:2)

回应更新的问题,

怎么样?
 ClearAll[AddGeometry];
 SetAttributes[AddGeometry, HoldAll];

 AddGeometry[scg_, tfg_, geo_] := Module[{}, AddAsChild[scg, tfg, geo]] /; MatchQ[geo, {_, {"GE", __}, __}];

 AddGeometry[scg_, tfg_, geo_] := (AddGeometry[scg, tfg, #] & /@ geo)

我测试了

 c1 = {4, {"GE", {"CU", {{0, 0, 0}, 4}}}, 5, 2};
 g = {{4, {"GE", {"CU", {{0, 0, 0}, 4}}}, 5, 
2}, {7, {"GE", {"CU", {{0, 3, 0}, 1}}}, 5, 
2}, {12, {"GE", {"CU", {{0, 5, 0}, 2}}}, 5, 2}};

AddGeometry[scg, tfg, c1]
AddGeometry[scg, tfg, g]

给了

AddAsChild[scg, tfg, {4, {"GE", {"CU", {{0, 0, 0}, 4}}}, 5, 2}]

 {AddAsChild[scg, tfg, {4, {"GE", {"CU", {{0, 0, 0}, 4}}}, 5, 2}], 
 AddAsChild[scg, tfg, {7, {"GE", {"CU", {{0, 3, 0}, 1}}}, 5, 2}], 
  AddAsChild[scg, tfg, {12, {"GE", {"CU", {{0, 5, 0}, 2}}}, 5, 2}]}

此外,如果AddAsChild完全与副作用相关,则可以使用Scan代替Map来避免获取Null的返回列表(或修改第二个定义)改为AddGeometry[scg_, tfg_, geo_] := (AddGeometry[scg, tfg, #]; & /@ geo)

答案 1 :(得分:1)

对不起,我在没有想到的情况下提前发布了一个无用的“解决方案”。你可以尝试:

ClearAll[AddGeometry]

SetAttributes[AddGeometry, HoldAll];

grpat = {_, {"GE", __}, __};

AddGeometry[scg_, tfg_, geo_] /; Head[geo] === List := 
 AddAsChild[scg, tfg, #] & /@ 
  Quiet[geo /. (x : grpat) | {x : grpat ..} :> {x}]

允许:

records =
  {{4, {"GE", {"CU", {{0, 0, 0}, 4}}}, 5, 2},
   {3, {"GE", {"CU", {{0, 1, 2}, 4}}}, 7, 1}};

AddGeometry[scg, tfg, records]

(* Out =
{AddAsChild[scg, tfg, {4, {"GE", {"CU", {{0, 0, 0}, 4}}}, 5, 2}], 
 AddAsChild[scg, tfg, {3, {"GE", {"CU", {{0, 1, 2}, 4}}}, 7, 1}]}
*)

如果您不希望AddGeometry输出,可以使用Scan而不是Map