Re:Let the Type System do the Work
by skybrian on Monday April 21, 2014 @01:28PM
(#7622312)
As an alternative, check out how Go does this. It's a nice compromise that lets you declare kilogram to be a float, and when used alone it treats it as a separate type, but it doesn't get in the way when you use it in an expression.
[ Parent
| on HN ]
That seems useful, but dangerous. If you specify (for some reason) both a centimeter and inches type, would you be able to mix them in expressions without warnings?
--------
Per [1] it seems that since both would be named types you wouldn't be able to assign one to the other without explicit conversions. If my reading is correct, then that addresses my concern. It's things like storing a `float` to a `inch` type that can happen without explicit conversion as long as `inch` has float as its base type.
[1] http://golang.org/ref/spec#Properties_of_types_and_values
They are separate types, not a type alias, but some conversions are automatic. The rule for assignability also affects comparisons and function calls (including expressions containing them), but apparently not all expressions like I thought?
> type Kilogram = Double
type synonym/alias.
In Haskell? I wouldn't do that. That improves readability, but it doesn't allow the compiler to enforce correct unit usage. If a Kilogram is just a synonym for a Double, you can pass it in where other meanings of Double are expected. E.g. you can pass Kilograms into a function that takes Pounds. Which you don't want to do.
That's why you want
newtype Kilogram = Kilogram Double
which has no runtime overhead but does enforce the fact the Kilogram is a distinct type.We probably wanna add to it to make it useful
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
newtype Kilogram = Kilogram Double deriving (Show, Eq, Ord, Num, Real, Fractional, Floating, ...)
And remind ourselves that Haskell is really quite expressive.Though unfortunately can't handle (mass * accel :: Newton) without swapping out the Prelude.
Ada does it all.
Yeah no kidding. I brought it up to show that you can have the same kind of thing that skybrian was talking about in Haskell.