[Issue 6788] std.range.pairwise?
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Tue Mar 12 12:04:55 PDT 2013
http://d.puremagic.com/issues/show_bug.cgi?id=6788
--- Comment #4 from bearophile_hugs at eml.cc 2013-03-12 12:04:54 PDT ---
Basic version for a random access range:
import std.range: ForeachType, isRandomAccessRange, hasLength;
import std.traits: Unqual, isNarrowString;
import std.typecons: Tuple;
struct Pairwise(Range) {
alias R = Unqual!Range;
alias Pair = Tuple!(ForeachType!R, "a", ForeachType!R, "b");
R _input;
size_t i, j;
this(Range r_) {
this._input = r_;
j = 1;
}
@property bool empty() {
return j >= _input.length;
}
@property Pair front() {
return Pair(_input[i], _input[j]);
}
void popFront() {
if (j >= _input.length - 1) {
i++;
j = i + 1;
} else {
j++;
}
}
}
Pairwise!Range pairwise(Range)(Range r)
if (isRandomAccessRange!Range && hasLength!Range && !isNarrowString!Range) {
return typeof(return)(r);
}
import std.stdio: writeln;
void main() {
(new int[0]).pairwise.writeln;
[10].pairwise.writeln;
[10, 20].pairwise.writeln;
[10, 20, 30].pairwise.writeln;
[10, 20, 30, 40].pairwise.writeln;
}
Once combinations() is implemented that code can be replaced with something
like:
auto pairwise(Range)(Range r) if (...) {
alias R = Unqual!Range;
alias Pair = Tuple!(ForeachType!R, "a", ForeachType!R, "b");
return combinations(r, 2).map(t => Pair(t.tupleof));
}
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list