It compiles because type
doesn't introduce a new distinct type:
A type synonym declaration introduces a new type that is equivalent to an old type.
[...]
Type synonyms are a convenient, but strictly syntactic, mechanism to make type signatures more readable. A synonym and its definition are completely interchangeable, [...]
Completely, without restrictions, at any level, including type signatures. You can see this with an even shorter example:
type Clown a b = Double
proof :: Clown a b -> Clown b a
proof = id
Since Clown a b
and Clown b a
are both Double
—regardless of the actual a
and b
—both can be exchanged for Double
, and proof
's type is Double -> Double
.
While your constraint limits the possible types for a
in Length a
, it doesn't actually change the semantics of the resulting type. Instead, use a newtype
:
data LengthUnit = Km | Meter
newtype Length (unit::LengthUnit) = MkLength {getLength :: Double}
onLength :: (Double -> Double) -> Length a -> Length a
onLength f = MkLength . f . getLength
divideByTwo ::Length l -> Length l
divideByTwo = onLength (/ 2)
getKm ::Double -> Length Km
getKm = MkLength
-- other code omitted
Now you will get the desired compile term errors, because Length Km
and Length Meter
are distinct types:
test.hs:25:44:
Couldn't match type 'Meter with 'Km
Expected type: Length 'Km
Actual type: Length 'Meter
In the second argument of `($)', namely `divideByTwo $ getMeter 1'
In the expression: isKm $ divideByTwo $ getMeter 1
In an equation for `this_should_not_compile_but_it_does':
this_should_not_compile_but_it_does
= isKm $ divideByTwo $ getMeter 1
test.hs:27:53:
Couldn't match type 'Meter with 'Km
Expected type: Length 'Km
Actual type: Length 'Meter
In the second argument of `($)', namely `getMeter 1'
In the expression: isKm $ getMeter 1
type
is not generative.Length Meter = Double = Length Km
. You have not introduced any unit-based distinctions here at all, I'm afraid. You may do better withnewtype
ordata
.type
is not generative, so I need to read up on what is generative and what is not :) thanks for guiding me towards the right direction.