D-不变范围的笛卡尔产品

  • 本文关键字:笛卡尔 范围 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/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

futhermore,如果第二个但第一个不可变的删除,则可以使用。

根据Phobos实现,是输入量的范围之一,另一个是向前的范围。为什么这样的模板约束?

我绝对不是D的专家,但是去年我问了一个类似的问题,乔纳森·M戴维斯的答案很棒。

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

最新更新