Hi, everyone. I’m new to Crystal and I have two language-design-related questions：
（1）Why do we need tuple?
I think maybe it’s because of the speed, the same reason in Python and in Elixir. Is performance of tuple being the whole reason to make Crystal’s designers choose to add tuple to the language?
（2）Why do we need named tuple?
It’s just a hash in Ruby. Why not directly use Hash?
Hi @ccmywish, welcome to the forum!
Short answer on the run, feel free to ask for follow ups.
Tuples (be they named or not) are not only more efficient than a hash, but they are also more precisely typed. In a hash, you need to assign the same type to all the entries (which in Crystal it can be a union of several types). With a tuple, each tuple field has its own, precise type. Perhaps a better sibling of a tuple is the
struct. In a sense, you could say that a (named) tuple is like an anonymous struct.
The typical use case for tuples is for returning multiple values. With a hash that’s ugly and error-prone.
The main reason why named tuples exist is to capture named arguments in a type-safe anonymous data structure. This is particularly useful for forwarding parameters:
args.class # => NamedTuple(string_parameter: String)
def bar(string_parameter : String)
foo(string_parameter: "foo") # => "FOO"
That’s also pretty much the single relevant use case. In all other cases it’s probably better to use a dedicated
struct type instead.
A named tuple type is basically like a struct type except that it doesn’t need an explicit definition (it’s created ad hoc) and it can only hold properties, no methods, inheritance etc.
Really helpful. Thank you!
By the way, a non-technical question:
How do you pronounce tuple？
Named tuples are fabulous because you can’t accidentally refer to a key by name and use a wrong name on accident…
Love to see some usage of IPA. I use pronunciation 2, though I don’t think I’ve ever heard that first one used.
I’ve always pronounced it as in quintuple/sextuple/septuple/octuple, since that’s the origin of the term. Same reason I pronounce “gif” with a hard G.