digitalmars.D.learn - Tuple deconstruction in Phobos
- IchorDev (22/22) Jul 20 Why does Phobos not provide a method to easily deconstruct
- Nick Treleaven (7/15) Jul 20 Instead of the `tie` assignment, you can just do:
- IchorDev (11/16) Jul 20 And here I was trying to use comma expressions for this like a
- Nick Treleaven (4/16) Jul 21 I think The lvalue sequence docs in template.dd were only updated
Why does Phobos not provide a method to easily deconstruct tuples? Here's a trivial implementation: ```d //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.
Jul 20
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: ```d import std.meta; AliasSeq!(y, x) = tupRetFn().expand; ```
Jul 20
On Saturday, 20 July 2024 at 20:48:29 UTC, Nick Treleaven wrote:Instead of the `tie` assignment, you can just do: ```d 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.
Jul 20
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:I think The lvalue sequence docs in template.dd were only updated in the last year to mention sequence assignment.Instead of the `tie` assignment, you can just do: ```d 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.Good idea.
Jul 21