The slides of the "Information Rich Programming with F# 3.0" talk
of Lang.NEXT 2012:
http://ecn.channel9.msdn.com/events/LangNEXT2012/LangNextDonnaFSharp.pptx
In the slide 6 titled "Simplicity Functional data" they compare
some F# functions to similar C# ones.
It shows a bit of syntax that makes tuple usage more handy, more
readable and shorter. I have discussed it a bit here:
http://d.puremagic.com/issues/show_bug.cgi?id=6544
------------------
The F# code shown on that slide:
let rotations (x, y, z) =
[ (x, y, z);
(z, x, y);
(y, z, x) ]
------------------
C#:
ReadOnlyCollection<Tuple<T,T,T>> Rotations<T>
(Tuple<T,T,T> t)
{
new ReadOnlyCollection<int>
(new Tuple<T,T,T>[]
{ new Tuple<T,T,T>(t.Item1,t.Item2,t.Item3);
new Tuple<T,T,T>(t.Item3,t.Item1,t.Item2);
new Tuple<T,T,T>(t.Item2,t.Item3,t.Item1); });
}
------------------
Similar D code:
import std.typecons;
auto rotations(T)(in Tuple!(T,T,T) t) pure nothrow {
return [tuple(t[0], t[1], t[2]),
tuple(t[2], t[0], t[1]),
tuple(t[1], t[2], t[0])];
}
void main() {
auto r = rotations(tuple(1, 2, 3));
}
------------------
Two Python2.6 versions:
def rotations((x, y, z)):
return [(x, y, z), (z, x, y), (y, z, x)]
rotations = lambda (x, y, z): [(x, y, z),
(z, x, y),
(y, z, x)]
print rotations((1, 2, 3))
------------------
In Haskell there is even an optional syntax to give names to both
the parts and the whole tuple:
twohead s@(x : xs) = x : s
main = print $ twohead [1,2,3]
That outputs:
[1,1,2,3]
------------------
While there is a good enough D syntax to support tuple unpacking
at the return point of a function, I don't know what syntax to
use in D for the naming of tuple parts in the function signature
(the same syntax is later usable for structs in switch-case).
Some possibilities:
This seems to works with all structs:
auto rotations(T)(Tuple!(T, T, T)(x, y, z)) {
Or:
auto rotations(T)(Tuple!(T, T, T) t(x, y, z)) {
Or the same syntax as the normal tuple unpacking syntax:
auto rotations(T)(auto (x, y, z)) {
auto rotations(T)((int x, int y, int z)) {
Or even:
auto rotations(T)(Tuple!(T x, T y, T z)) {
Please take a look at the issue 6544 for more info.
Bye,
bearophile