Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 64 additions & 38 deletions std/algorithm/setops.d
Original file line number Diff line number Diff line change
Expand Up @@ -365,59 +365,78 @@ if (ranges.length >= 2 &&
// For infinite ranges or non-forward ranges, we fall back to the old
// implementation which expands an exponential number of templates.
import std.typecons : tuple;
import std.range.primitives : hasLength;
import std.algorithm : allSatisfy;

static struct Result
{
RR ranges;
RR current;
bool empty = true;
{
RR ranges;
RR current;
bool empty = true;

this(RR _ranges)
this(RR _ranges)
{
ranges = _ranges;
empty = false;
foreach (i, r; ranges)
{
ranges = _ranges;
empty = false;
foreach (i, r; ranges)
{
current[i] = r.save;
if (current[i].empty)
empty = true;
}
current[i] = r.save;
if (current[i].empty)
empty = true;
}
@property auto front()
}

@property auto front()
{
import std.algorithm.internal : algoFormat;
import std.range : iota;
return mixin(algoFormat("tuple(%(current[%d].front%|,%))",
iota(0, current.length)));
}

void popFront() scope
{
foreach_reverse (i, ref r; current)
{
import std.algorithm.internal : algoFormat;
import std.range : iota;
return mixin(algoFormat("tuple(%(current[%d].front%|,%))",
iota(0, current.length)));
r.popFront();
if (!r.empty) break;

static if (i == 0)
empty = true;
else
r = ranges[i].save; // rollover
}
void popFront() scope
{
foreach_reverse (i, ref r; current)
{
r.popFront();
if (!r.empty) break;
}

static if (i == 0)
empty = true;
else
r = ranges[i].save; // rollover
}
@property Result save() return scope
{
Result copy = this;
foreach (i, r; ranges)
{
copy.ranges[i] = ranges[i].save;
copy.current[i] = current[i].save;
}
@property Result save() return scope
return copy;
}

static if (allSatisfy!(hasLength, RR))
{
@property size_t length() const
{
Result copy = this;
foreach (i, r; ranges)
size_t result = 1;
foreach (r; ranges)
{
copy.ranges[i] = ranges[i].save;
copy.current[i] = current[i].save;
result *= r.length;
}
return copy;
return result;
}
}
static assert(isForwardRange!Result, Result.stringof ~ " must be a forward"
~ " range");
}

static assert(isForwardRange!Result,
Result.stringof ~ " must be a forward range");

return Result(ranges);
return Result(ranges);
}

// cartesian product of empty ranges should be empty
Expand All @@ -436,6 +455,13 @@ if (ranges.length >= 2 &&
assert(cprod2.empty);
foreach (_; cprod2) {} // should not crash
}
@safe unittest
{
import std.algorithm.setops;

assert(cartesianProduct([1,2], [3,4]).length == 4);
assert(cartesianProduct([1,2,3], [4,5]).length == 6);
}

@safe unittest
{
Expand Down