3 ms·
This kind of thing is why I'd favour two different types of numeric types: - "Number", which would be the generic DWIM arithmetic type. In your example both x
by pjc50 9y ago
This kind of thing is why I'd favour two different types of numeric types:
- "Number", which would be the generic DWIM arithmetic type. In your example both x and the literals would be Number.
- Hyper-specified arithmetic types. Not just number of bits and signedness, but also overflow and trap behaviour. Less convenient to use - you can't easily add a "32bit signed wrap on overflow" to "16 bit unsigned saturate on overflow", but have the advantage that there is no unspecified behaviour. This also allows the user to make use of machine-provided saturate and overflow behaviour where present.
- mannykannot 9y agoI see where you are coming from, but C offers a cautionary tale: It offers more choices than most languages, and that creates a number of traps for the unwary. Maybe, however, that is only because it allows mixed-type expressions?
- pjc50 9y agoChoice for the programmer, or choice for the implementer? Part of the problem of C is the amount of stuff with was left as a choice for the implementers on a particular platform and therefore could not be safely assumed to be universal. Forcing the programmer to enumerate what they actually want from their "fast machine integers" avoids that. C offers a fairly small choice of types to the programmer, certainly compared to one of the ML/Haskell style of language. It doesn't even have a proper "string" type! C doesn't exactly allow mixed-type expressions, it just performs a lot of type coercion and reinterpretation. Which is another one of those things that trades safety for convenience in so many languages. Type flexibility is responsible for most of the wtf type moments in Javascript: https://www.destroyallsoftware.com/talks/wat https://www.destroyallsoftware.com/talks/wat
- DoofusOfDeath 9y agoI've been thinking about something similar. My idea is to let programmers specify various constraints they care about on numeric-typed variables, including min/max value. Then the compiler has the freedom to choose any representation(s) it cares to that matches the constraints. For complicated constraints that are difficult to prove at static-compilation time, some checks might be deferred until linktime (when static call contexts are available) or runtime.
- indexerror 9y agoThis is the approach that Kotlin takes (albeit with boxed primitive types). Float, Integer, Long - all are subtypes of Number.