2 ms·
> How would a basic type system protect against incorrectly interpreting an imperial floating point value as a metric floating point value? You could wrap your
by joshmarlow 10y ago
> How would a basic type system protect against incorrectly interpreting an imperial floating point value as a metric floating point value?
You could wrap your value in a typed data structure:
enum LengthUnit {
Feet(f64),
Meters(f64),
}
And provide conversion functions between them, then only operate on one type, `LengthUnit::Meters` and throw errors if `LengthUnit::Feet` is passed in.
I'm using Rust syntax here because it's fresher on my mind, but you could do the same with Haskell, OCaml, F#, etc. IIRC, OCaml would optimize away the outer structure so you wouldn't have much/if any performance hit. Presumably compilers for the other languages could/would do the same.
EDIT: for formatting and clarity.