3 ms·
It's more precise to think of unit as an empty tuple. A tuple is like an ad-hoc struct without names for the fields, so `(int, string)` is like `struct MyTuple
by zamalek 2y ago
It's more precise to think of unit as an empty tuple. A tuple is like an ad-hoc struct without names for the fields, so `(int, string)` is like `struct MyTuple { int a; string b; }`. An empty tuple would be `()` (which is the syntax for unit in many languages), meaning `struct MyTuple {}`. If you think about it, that's about the closest you can get to "nothing" without invoking type system handwavium (like void, which is basically "unit without the good parts but that can also mean anything").
You can do clever stuff with it, for example `HashMap<string, ()>` is practically identical to `HashSet<string>` (depending on how clever the compiler is, possibly actually identical).
- chills 2y agoI don't think it's particularly useful to think of unit as an empty tuple specifically, that is just an arbitrary but convenient definition for it. Really a unit type is just one that contains only a single value. This is a unit in the same way that 1 is a unit for the integers. With some hand waving it is an identity for product types, for example (int, ()) is the "same" (xxxmorphic yada yada) as int
- winwang 2y agoMildly disagree with your first statement. Well, I mostly agree that it's not particularly helpful for newcomers. As a 0-tuple, it becomes a specific case of a more general concept -- there is some beauty/usefulness in not having to have a "special" construct for "Unit", which is (in a sense) not just "any" unit type. It also "justifies" the syntax of `()` and notes that it is a product type, all the while fitting into the idea of the "cardinality" of `(a1, a2, ..., an)` being the product of the cardinalities of each of its type params.
- fuzztester 2y ago>you think about it, that's about the closest you can get to "nothing" Some other options could be to use None (like Python does) or Nil or Nothing itself, or even ReturnsNothing to be more explicit, or even the Pascal-style procedure keyword, instead of the function keyword, for a sub routine that returns nothing.
- mrkeen 2y agoThen you have to double-up all your higher-order functions, like Java 8 futures with their thenApply vs thenAccept.