Difference between revisions of "Non-trivial type synonyms"
Jump to navigation
Jump to search
BrettGiles (talk | contribs) m (Adding Category) |
BrettGiles (talk | contribs) m (Correction phantom type links) |
||
Line 44: | Line 44: | ||
{- or just use Miles, though this is harder to excise later -} |
{- or just use Miles, though this is harder to excise later -} |
||
</haskell> |
</haskell> |
||
− | For tracking more complex units, you may be able to get some of the way by using [[Phantom |
+ | For tracking more complex units, you may be able to get some of the way by using [[Phantom type]]s or creative use of [[Functional dependencies]]. |
==See also== |
==See also== |
||
− | * For an example toy implementation using [[Phantom |
+ | * For an example toy implementation using [[Phantom type]]s & [[Functional dependencies]], see [[Dimensionalized numbers]] |
* [[Wrapper types]]. |
* [[Wrapper types]]. |
||
Revision as of 21:49, 2 October 2006
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.
Alternate Miles etc. definitions
No need to change things : The functions toMiles and fromMiles is already effectively id !
A "newtype" definition just generates a new type whose implementation is the same as the old one.
The constructor (and possibly selector) really does nothing except coerce between the new type and the old one.
So as undefined
is Haskells notation for bottom
toMiles undefined === undefined
which isn't the case if we use a "data" definition.
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.
See also
- For an example toy implementation using Phantom types & Functional dependencies, see Dimensionalized numbers
- Wrapper types.