Non-trivial type synonyms
From HaskellWiki
1 Make the type system work for you
To avoid Miles/Km , feet/metres goofs:
Rather than
type Miles = Int
use
newtype Miles = Miles Int
together with
toMiles :: Int -> Miles fromMiles :: Miles -> Int
these can be redefined to be "id" later, after the code is stablized.
2 Alternate Miles etc. definitions
No need to change things : The functions toMiles and fromMiles is already effectively id !
Anewtype
The constructor (and possibly selector) really does nothing except coerce between the new type and the old one.
So asundefined
toMiles undefined === undefined
data
Structures might be a bit more convenient here.
newtype Miles = Miles { fromMiles :: Int } toMiles = Miles {- or just use Miles, though this is harder to excise later -}
For tracking more complex units, you may be able to get some of the way by using phantom types or creative use of functional dependencies.
3 See also
- For an example toy implementation using phantom types & functional dependencies, see dimensionalized numbers
- Wrapper types.
