Tuples citizenship
bearophile
bearophileHUGS at lycos.com
Thu Mar 1 15:57:15 PST 2012
Jonathan M Davis:
> When you're looking to mutate existing variables in the caller, using out
> parameters results in cleaner code. Tuples are inherently messier, because you
> have to deal with multiple return values.
out arguments have two risks:
- If you assign a value to a variable and then use it to call a function, the precedent value is ignored and overwritten.
- If in a function you forget to assign an out argument, the D compiler produces no errors.
Both source of bugs are not present with tuples.
> They also often do poorly when you
> need to use the functional programming,
As you know functional languages use tuples all the time.
> At other times, tuples are nicer - like when you actually _want_ the return
> value packed together (though often, if that's what you really want, a struct
> might be better).
Defining a struct makes your code messier. D tuples support named fields too, so the advantage of using a struct is limited.
> And if you're not looking to assign the parts of a tuple to
> existing variables, then they're not quite as bad as when you are, since you
> don't necessarily have to then assign the pieces to other variables.
There are parts of your post that I don't fully understand.
> Both have value, though if you need a lot of either, you should probably
> consider whether a struct or class would suit what you're doing better.
For most usages of a tuple a class instance means useless heap activity and more work for the GC.
Using a struct to return the results of a function is sometimes acceptable, but most times I don't use tuples for that purpose. Consider this code in my original post, defining two static structs doesn't do much good to such kind of code:
Tuple!(char,int)[] pairs2 = frequences.pairs;
schwartzSort!(c_f => tuple(-c_f[1], c_f[0]))(pairs2);
foreach (c_f; pairs2)
writeln(c_f[1], " ", c_f[0]);
Tuples are often defined and used on the fly, in-place.
Bye,
bearophile
More information about the Digitalmars-d
mailing list