Auto tuple declaration
bearophile
bearophileHUGS at lycos.com
Sun Aug 28 03:39:03 PDT 2011
Kenji hara:
> I have posted pull request.
> https://github.com/D-Programming-Language/dmd/pull/341
Thank you. If it works well then it will be a significant improvement for D.
I invite people here to try it and use it a bit, and look for possible corner cases or troubles :-)
This is an example of D2 code that uses tuples (it's a translation of OcaML code), the new syntax is able to simplify this code, making it better:
http://rosettacode.org/wiki/Color_quantization#D
-------------------
There are two more cases where the tuple unpacking syntax will be useful, that aren't supported by pull 341 (the array were supported in a precedent version of it):
void main() {
int[] a1 = [1, 2];
int[2] a11;
a11 = a1; // runtime test
(auto x, y) = a1; // runtime test
int[2] a2 = [1, 2];
(auto z, w) = a2; // no need to verify a2 length at runtime here
}
import std.string;
void main() {
string s = " foo bar ";
(auto sa, sb) = s.split();
}
import std.algorithm, std.conv, std.string;
void main() {
string s = " 15 27";
(int x, int y) = map!(to!int)(splitter(s));
}
See here for more info:
http://d.puremagic.com/issues/show_bug.cgi?id=6383
-----------------
This OCaML function returns the sum of two RGB colors (here represented with a 3-tuple of FP values), this is typical code:
let rgb_add (r1,g1,b1) (r2,g2,b2) =
(r1 +. r2,
g1 +. g2,
b1 +. b2)
A possible D syntax (a better syntax is possible):
auto rgbAdd(Color(r1,g1,b1), Color(r2,g2,b2)) {
return Color(r1 + r2, g1 + g2, b1 + b2);
}
Note that in some cases you can't use the sometuple.tupleof syntax:
bool isGreeny(Color(r, g, b)) {
return g > 2;
}
auto r = filter!isGreeny([Color(1,2,3), Color(4,5,6)]);
See here for more info:
http://d.puremagic.com/issues/show_bug.cgi?id=6544
Bye,
bearophile
More information about the Digitalmars-d
mailing list