Tuple unpacking example, and to!
bearophile
bearophileHUGS at lycos.com
Sat May 8 17:39:30 PDT 2010
Once in a while it's positive to show simple usages and comparisons. This is a little comparison that shows why tuple unpacking is handy, from real-life programming.
This is just a little thing, but such things pile up one over the other to make a language more handy than another one.
Python V.2.x:
foo, bar, baz = map(int, readline().split())
Python V.3.x:
foo, bar, baz = list(map(int, readline().split()))
D2 + Phobos:
long[] foo_bar_baz = array(map!(to!(long, string))(readln().split()));
assert(foo_bar_baz.length == 3);
long foo = foo_bar_baz[0];
long bar = foo_bar_baz[1];
long baz = foo_bar_baz[2];
If the to!() template arguments are split in two nested templates then that code can compile with a syntax like this, that's a bit more readable and simpler to write:
long[] foo_bar_baz = array(map!(to!long)(readln().split()));
This test program works:
import std.stdio: writeln;
import std.conv: to;
import std.algorithm: array, map;
template to_(Tout) {
Tout to_(Tin)(Tin x) {
return to!(Tout, Tin)(x);
}
}
void main() {
string[] data = ["1", "2", "3"];
int[] arr = array(map!(to_!int)(data));
writeln(arr);
}
But then unfortunately when you want specify manually both types of to_ this doesn't compile:
writeln((to_!(string))!(string)("10"));
DMD returns:
test.d(18): C style cast illegal, use cast(string)"10"
test.d(18): C style cast illegal, use cast(to_!(string))!cast(string)"10"
and you have to use an auxiliary alias:
alias to_!(int) to_int;
writeln(to_int!(string)("10"));
You can't solve this problem with an alias:
alias to to_;
That causes the error:
test.d(10): Error: alias test.to_ conflicts with template test.to_(Tout) at test.d(5)
But this works:
import std.stdio: writeln;
import std.conv: to;
import std.algorithm: array, map;
template to_(Tout) {
Tout to_(Tin)(Tin x) {
return to!(Tout, Tin)(x);
}
}
Tout to_(Tout, Tin)(Tin x) {
return to!(Tout, Tin)(x);
}
void main() {
string[] data = ["1", "2", "3"];
int[] arr = array(map!(to_!int)(data));
writeln(arr);
writeln(to_!int("10"));
writeln(to_!(int, string)("20"));
}
So I can suggest this as a little enhancement for Phobos2. (Later on this I can even put a patch in Bugzilla).
Bye,
bearophile
More information about the Digitalmars-d
mailing list