[Haskell-cafe] numerical subtyping

Derek Elkins ddarius at hotpop.com
Tue Dec 7 22:27:09 EST 2004

> Is there a standard Haskell trick for checking run-time assignment to 
> data types? I'd like a data type of Probability that ensures its
> Double argument is between 0 and 1.
> Jim

A fairly common technique to achieve this is smart constructors
(apparently also called factory functions).


You simply enforce the invariant on construction.  For your example, it
would look like,

newtype Probability = Probability Double

probability p | 0.0 <= p && p <= 1.0 = Probability p

unProbability (Probability p) = p

Simply don't export Probability's constructor and it will be impossible
to create a Probability with a value outside of [0,1].  However, you may
want to export the constructor, or alternatively, export a function with
a name like unsafeProbability (= Probability) for situations where you
can statically decide that the invariant will hold if the superfluous
checking costs too much, which doesn't seem particularly likely in this
case.  Providing a function of type Double -> Maybe Probability is also
likely a good idea.

More information about the Haskell-Cafe mailing list