D 不变范围的笛卡尔积

D 不变范围的笛卡尔积,d,phobos,D,Phobos,为什么我们不能计算两个不变范围的笛卡尔积 以下代码: import std.stdio; import std.algorithm; void main() { immutable int[] B = [ 1, 2, 3 ]; immutable int[] C = [ 4, 5, 6 ]; auto BC = cartesianProduct(B, C); writeln(BC); } 抛出: /usr/include/dmd/phobos/std/ra

为什么我们不能计算两个不变范围的笛卡尔积

以下代码:

import std.stdio;
import std.algorithm;

void main() {

    immutable int[] B = [ 1, 2, 3 ];
    immutable int[] C = [ 4, 5, 6 ];
    auto BC = cartesianProduct(B, C);

    writeln(BC);
}
抛出:

/usr/include/dmd/phobos/std/range.d(4199): Error: cannot modify struct result._ranges_field_1 Repeat!(immutable(int)) with immutable members
/usr/include/dmd/phobos/std/range.d(4503): Error: template instance std.range.Zip!(immutable(int)[], Repeat!(immutable(int))) error instantiating
/usr/include/dmd/phobos/std/algorithm.d(11674):        instantiated from here: zip!(immutable(int)[], Repeat!(immutable(int)))
laurent_test.d(8):        instantiated from here: cartesianProduct!(immutable(int)[], immutable(int)[])
/usr/include/dmd/phobos/std/algorithm.d(11674): Error: template instance std.range.zip!(immutable(int)[], Repeat!(immutable(int))) error instantiating
laurent_test.d(8):        instantiated from here: cartesianProduct!(immutable(int)[], immutable(int)[])
laurent_test.d(8): Error: template instance std.algorithm.cartesianProduct!(immutable(int)[], immutable(int)[]) error instantiating
此外,如果第二个但第一个不可变的被删除,它就会工作


根据phobos的实现,其中一个范围是inputRange,另一个是forwardRange。为什么会有这样的模板约束?

我肯定不是D方面的专家,但去年我问了a,这非常好

TL;DR:范围不能是不变的,因为它不遵守以下4条规则:

R r = void;       // can define a range object
if (r.empty) {}   // can test for empty
r.popFront();     // can invoke popFront()
auto h = r.front; // can get the front of the range

你能猜出罪犯的指纹吗
popFront

实际上,静态断言(isForwardRange!(typeof(B)))失败。很抱歉,我不接受这个答案,因为我不了解所有内容。例如,chain()函数可以工作,因为它使用了Unqual模板。计算笛卡尔积不需要popFront,不是吗?为什么我们需要一个输入和一个前向范围?是的,我不认为这是问题所在,因为即使明确地对它进行切片(这应该会删除顶级不可变项),也不起作用。看起来在这里的某个地方,它试图在内部分配给类型,这就是它被绊倒的原因;我倾向于认为它是实现中的一个潜在缺陷,但还没有检查源代码。请注意,人们通常想要的是不可变成员的可变数组,例如,
immutable(int)[]
immutable int[]
相当于
immutable(int[])
,它比第一种类型更具限制性。不能说它适用于你的问题,尤其是因为它不能解决问题。