[Issue 8155] New: Deprecate std.range.lockstep
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Sun May 27 14:19:04 PDT 2012
http://d.puremagic.com/issues/show_bug.cgi?id=8155
Summary: Deprecate std.range.lockstep
Product: D
Version: D2
Platform: All
OS/Version: All
Status: NEW
Severity: enhancement
Priority: P2
Component: Phobos
AssignedTo: nobody at puremagic.com
ReportedBy: bearophile_hugs at eml.cc
--- Comment #0 from bearophile_hugs at eml.cc 2012-05-27 14:20:51 PDT ---
I suggest to deprecate std.range.lockstep because with the recent improvements
in tuple unpacking, std.range.zip is able to replace its the main purpose, this
now works:
import std.stdio, std.range;
void main() {
foreach (a, b; zip([1,2], ["red", "blue"]))
writeln(a, " ", b);
}
lockstep() is also able to iterate with an index variable, zip() is not able to
do it:
import std.stdio, std.range;
void main() {
foreach (i, a, b; lockstep([1,2], ["red", "blue"]))
writeln(i, " ", a, " ", b);
}
But from my experience the need of an indexing variable on a zipped iteraton is
not so common, and the there are other solutions, like:
import std.stdio, std.range;
void main() {
foreach (i, a, b; lockstep(iota([1,2].length), [1,2], ["red", "blue"]))
writeln(i, " ", a, " ", b);
}
A better solution (hopefully not too much slower) is to use enumerate(zip()),
as in Python and Haskell, see Issue 5550 :
import std.stdio, std.algorithm, std.range, std.typecons, std.traits,
std.array;
struct Enumerate(R) {
R r;
int i;
@property bool empty() {
return this.r.empty;
}
@property Tuple!(typeof(this.i), typeof(R.init.front)) front() {
return typeof(return)(i, this.r.front);
}
void popFront() {
this.r.popFront();
this.i++;
}
}
Enumerate!R enumerate(R)(R range, int start=0) if (isInputRange!R) {
return Enumerate!R(range, start);
}
void main() {
foreach (i, a, b; enumerate(zip([1,2], ["red", "blue"])))
writeln(i, " ", a, " ", b);
}
Or even use countFrom (similar to Python itertools.count()), see Issue 7839 :
import std.stdio, std.range;
struct CountFrom(T) {
T n;
this(T n_) { this.n = n_; }
const bool empty = false;
@property T front() { return n; }
void popFront() { /* n++; */ n += 1; }
}
CountFrom!T countFrom(T)(T start) { return CountFrom!T(start); }
CountFrom!T countFrom(T)() { return CountFrom!T(cast(T)0); }
void main() {
foreach (i, a, b; zip(countFrom!size_t(), [1,2], ["red", "blue"]))
writeln(i, " ", a, " ", b);
}
(For Phobos there are much more commonly useful functions, like amap/afilter
that mean array(map()) and array(filter()) that are useful everywhere and
shorten/simplify the code).
--
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