On Tuesday, 6 February 2024 at 07:17:34 UTC, Profunctor wrote:
On Monday, 5 February 2024 at 21:12:58 UTC, Gary Chike wrote:
For either of these, one can "unpack" some or none of a Tuple's
fields, and both can be modified to ignore any field to
simulate `val (name, _, prof) = ("John Doe", 32, "Chemist")`.
Thank you Profunctor! This gives me a lot to chew on. :)
I had to ask [Anthropic
Claude2](https://www.anthropic.com/news/claude-2) to help me
understand what's going on. I placed the response below for other
newbs to the D language:
---
This is a very clever alternative approach to tuple unpacking in
D suggested on the forums! Here is how it works:
1. Define a `named` template that takes a tuple and field names.
It returns a new tuple with those field names applied to the
original tuple's values.
2. Access the new named tuple naturally with dot notation
```d
auto user = getUser();
auto namedUser = user.named!("name", "age");
writeln(namedUser.name);
```
Similarly, the `Unpack` mixin template defines variables in the
current scope matching the tuple by name:
```d
mixin Unpack!(user, "name", "age");
writeln(name); // accessed naturally now
```
So both work by naming the anonymous tuple fields, allowing clean
access without indexes.
The pros of this approach:
- No AliasSeq, very straightforward
- Custom field names
- Clean syntax after setup
The cons:
- More verbose initial setup
- Doesn't modify original tuple
But overall it's an elegant way to indirectly add names to tuples
in D for ergonomic access. Nice find!