2 ms·
A tuple is the generic term for a pair, triple, etc. It's a collection of data of heterogeneous types, unlike an array which is homogeneous. When the members
by peeters 7y ago
A tuple is the generic term for a pair, triple, etc. It's a collection of data of heterogeneous types, unlike an array which is homogeneous. When the members are unnamed, the data is indexed by its position like an array.
E.g. a method could return an unnamed tuple ("foo", 7) which might have type (String, int).
In some languages like ML, having tuples is such a fundamental part of the language that things like functions always act on a single argument which is actually just a tuple. So max(5, 5) is a function that takes a tuple of two ints as its parameter.
When you have tuples as a first-class concept, you can start to do some interesting shortcuts like:
(b, a) = (a, b); // swap two variables with no intermediate
or
String (first, last) = name;
This is called deconstruction, where you extract a tuple into variables representing its members. This is common in a ton of languages (Typescript, C#, ML, Scala, Python, etc). It also forms a cornerstone of pattern matching expressions in some languages (Scala, Haskell) where you can create a condition and simultaneously assign the data you care about to variables that can then be used in that branch. Scala pseudocode:
sum(list: ConsList<int>) {
return list match {
Empty(): 0;
Node(first, rest): first + sum(rest);
}
}