为什么 Math::Cartesian::Product 返回受祝福的对象?
我注意到 Math::Cartesian::Product 返回一个数组受祝福的对象而不是简单的数组数组。我不明白为什么。我实际上需要做一些额外的工作(除非祝福)才能使用结果......
I noticed Math::Cartesian::Product returns an array of blessed objects instead of a simple array of arrays. I couldn't figure out why. I actually need to do some extra work (unbless) to use the results...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我向 List::Gen 添加了一个
cartesian
函数最近:笛卡尔代码 LIST_of_ARRAYREF
cartesian
计算任意数量的数组引用的笛卡尔积,每个数组引用可以是任意大小。返回一个生成器返回的“生成器”是一个惰性绑定数组,它将在需要时生成值。还有迭代和其他访问器方法:
我不知道您将使用的集合有多大,但使用上述方法的优点是生成器的存储要求保持为 O(1)< /code>
只计算集合中的 6 个元素,并且不存储任何内容。
从示例中可以看出,cartesian 本身的返回值是一个生成器对象,但该对象的后续返回值是传递给 cartesian 的 coderef 返回的值。因此,如果您想要数组引用,就很简单:
cartesian {\@_} ...
另外,您需要做哪些额外的工作来处理受祝福的引用?除了 ref 将返回的内容之外,受祝福的数组在任何意义上仍然是一个数组。如果您正在编写基于引用类型的开关逻辑,则应该使用
Scalar::Util
的reftype
。I added a
cartesian
function to List::Gen recently:cartesian CODE LIST_of_ARRAYREF
cartesian
computes the cartesian product of any number of array refs, each which can be any size. returns a generatorThe "generator" returned is a lazy tied array that will generate values when asked for them. There are also iterative and other accessor methods:
I don't know how large the sets you will be working with are, but the advantage to using the above approach is that the storage requirements for the generator remain
O(1)
which calculates only 6 elements of the set, and stores nothing.
As you can see from the examples, the return value of
cartesian
itself is a generator object, but that object's subsequent return values are whatever the coderef passed tocartesian
returns. So if you want array references, it's as simple as:cartesian {\@_} ...
Also, what extra work did you have to do to deal with the blessed reference? A blessed array is still an array in every sense except for what
ref
will return. If you are writing switch logic based on reference type,Scalar::Util
'sreftype
is what you should use.一种替代方法是模块 Set::CrossProduct,它将产生普通的、未受祝福的数组参考文献:
或者一次获取所有元组:
One alternative is the module Set::CrossProduct, which will yield ordinary, unblessed array references:
Or get all tuples at once:
它祝福由
cartesian
返回的数组,以便当运行如下所示的某些代码时...它可以检测到
$b
是先前调用模块的结果。进行笛卡尔积运算是一件微不足道的事情,如果该模块返回的数据不符合您的需求,请考虑从头开始自己编写该运算。
无论如何,检查模块源代码会发现它并不太好。
It blesses the arrays returned by
cartesian
so that when some code as the following is run... it can detect that
$b
is the result of a previous call to the module.Doing a cartesian product operation is something trivial, if the data as returned by that module does not fit your needs, consider writting the operation yourself from scratch.
Anyway, inspecting the module source code reveals it is not too great.