4 ms·
One of the first programming languages I learned was TI BASIC on the TI-89. It had an excellent units (refinement types) system: you could define an expression
by SAI_Peregrinus 4y ago
One of the first programming languages I learned was TI BASIC on the TI-89. It had an excellent units (refinement types) system: you could define an expression as a "unit" by prefixing a variable with an underscore, and it came with a bunch of built-in units. A unit expression could thereby automatically convert between types as needed, outputing the base unit.
E.g. `5_dollars + 8_cents` would output `508_cents`. There was also a conversion operator you could use to change the output unit, so `5_dollars + 8_cents→_dollars` would output `5.08_dollars`.
It even worked for more complicated derived units, so e.g. `8_m * 5_kg / (3_s * 4_s)` returns `3.333_N`.
- ant6n 4y agoLooks neat. Of course you can do this in c++.
- SAI_Peregrinus 4y agoOf course, templates are sufficiently complex metaprogramming to achieve this. But it's not a language built-in, or even part of the standard library. F# has a refinement type system built in (which allows this), and of course Haskell and Idris are sufficiently capable in their type systems to trivially support it, but none of those are particularly mainstream general-purpose programming languages. Mainstream languages pretty much all need some sort of library for it, which is unfortunate since they're extremely useful in many common programming problems.
- ant6n 4y agoIn C++, you can do this with custom literals, not meta programming: https://en.cppreference.com/w/cpp/language/user_literal https://en.cppreference.com/w/cpp/language/user_literal One would have to make a library with various classes representing various units, plus the (implicit) conversion between them. It´s probably something that exists somewhere.
- wtallis 4y agoI think TI probably copied that from the HP 48, which used more or less the same syntax. The only difference is that the calculation you show would not have been automatically reduced to _N, but you could use the CONVERT or UFACT commands to get Newtons from kg*m/s^2. In practice, HP's UI made it a lot easier to manipulate quantities tagged with units: hitting the softkey for a unit would multiply the current value by that unit, and using the two shift keys you could either divide by that unit or convert to that unit. If you made a custom menu to put the handful of units relevant to your current problem domain all close at hand, you would need very few extra keystrokes compared with calculating without using the units system. That ease of use is vital; opt-in type safety should be as easy to use as possible, so that users aren't tempted to fall back to the simpler, less safe method.