On Friday, 22 November 2024 at 16:36:43 UTC, Andrew wrote:
I'm getting started using D for some small personal projects
and one thing I wanted to do was use a helper function for a
tuple. I declared the function like this:
string getOrZeroth(Tuple!(string, string, string) tup, int
i) pure {
return tup[i] == "" ? tup[0] : tup[i];
}
and would like to use it like this:
auto foo = tuple("a", "", "c");
writeln(foo.getOrZeroth(1)); // prints a
I'm guessing you have some Python in your background, where
"tuple" means "read-only list (e.g., array)". Your "tuple" here
actually wants to be an immutable array of string, and then life
is good. Tuples are a way to have an array of dissimilar
types--but then run-time generated values used to index the tuple
will add--in the general case--all sorts of imponderables to the
compiler's type treatment.
You could claim it can do it for the special case of a tuple
holding only one type, but why bother? We already have arrays.
You might want to study what it takes to walk the fields of a
type (Type.tupleof). The foreach is actually unrolled at compile
time for each field. From one of my own exercises, a mini-CSV
module:
https://sources.vsta.org:7100/dlang/file?name=tiny/csv.d&ci=tip