gpt4 book ai didi

wolfram-mathematica - 请求代码审查和改进建议(是 : Question on making a function Listable )

转载 作者:行者123 更新时间:2023-12-04 06:23:17 24 4
gpt4 key购买 nike

根据 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]
    ]

    最佳答案

    回应更新的问题,怎么样

     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 的返回列表s(或将第二个定义修改为 AddGeometry[scg_, tfg_, geo_] := (AddGeometry[scg, tfg, #]; & /@ geo))。

    关于wolfram-mathematica - 请求代码审查和改进建议(是 : Question on making a function Listable ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6315364/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com