Thread overview
Tuple deconstruction in Phobos
Jul 20, 2024
IchorDev
Jul 20, 2024
Nick Treleaven
Jul 21, 2024
IchorDev
Jul 21, 2024
Nick Treleaven
July 20, 2024

Why does Phobos not provide a method to easily deconstruct tuples? Here's a trivial implementation:

//Similar to C++'s `std::tie`. Can anyone tell me why it's called `tie`?
void tie(T...)(typeof(T) src){
	static foreach(ind, i; src){
		T[ind] = i;
	}
}

//Usage example:
import std.stdio, std.typecons;

auto tupRetFn() => tuple(47, "test!");

void main(){
	string x = "discarded";
	int y;
	tie!(y, x) = tupRetFn().expand;
	writeln(x,", ",y);
}

Not having this is like if Phobos didn't have AliasSeq. Yes you can make your own, but it's wasteful boilerplate.

July 20, 2024

On Saturday, 20 July 2024 at 14:02:21 UTC, IchorDev wrote:

>

Why does Phobos not provide a method to easily deconstruct tuples? Here's a trivial implementation:
...
tie!(y, x) = tupRetFn().expand;
writeln(x,", ",y);
}

Not having this is like if Phobos didn't have `AliasSeq`. Yes you can make your own, but it's wasteful boilerplate.

Instead of the tie assignment, you can just do:

	import std.meta;
	AliasSeq!(y, x) = tupRetFn().expand;
July 21, 2024

On Saturday, 20 July 2024 at 20:48:29 UTC, Nick Treleaven wrote:

>

Instead of the tie assignment, you can just do:

	import std.meta;
	AliasSeq!(y, x) = tupRetFn().expand;

And here I was trying to use comma expressions for this like a buffoon! Of course they didn't work, but I'm pleasantly surprised that using a sequence does. I should really PR std.typecons to add a couple of examples of this, because I think a lot of people will have overlooked it.
I honestly thought there was no way to do this in D for the longest time until I saw some C++ code using std::tie and I realised that obviously the same thing is doable in D using opAssign, and then refined it to use UFCS because the syntax Tie!(y,x)() was a bit clunky.

July 21, 2024

On Sunday, 21 July 2024 at 04:05:52 UTC, IchorDev wrote:

>

On Saturday, 20 July 2024 at 20:48:29 UTC, Nick Treleaven wrote:

>

Instead of the tie assignment, you can just do:

	import std.meta;
	AliasSeq!(y, x) = tupRetFn().expand;

And here I was trying to use comma expressions for this like a buffoon! Of course they didn't work, but I'm pleasantly surprised that using a sequence does.

I think The lvalue sequence docs in template.dd were only updated in the last year to mention sequence assignment.

>

I should really PR std.typecons to add a couple of examples of this, because I think a lot of people will have overlooked it.

Good idea.