[Haskell-beginners] Re: Restricting integers in a type?
es at ertes.de
Tue Dec 30 04:13:15 EST 2008
Colin Paul Adams <colin at colina.demon.co.uk> wrote:
> >>>>> "Ertugrul" == Ertugrul Soeylemez <es at ertes.de> writes:
> >> That would seem to allow x = -3 and y = 13, for instance.
> Ertugrul> Not if you disallow an x = -3 and y = 13 to happen in
> Ertugrul> the first place. Haskell's module and type system
> Ertugrul> allows you to do that.
> Can you explain how to do that please?
module Even (Even) where
newtype Even a = Even a
deriving (Eq, Show)
instance Integral a => Num (Even a) where
Even a + Even b = Even (a+b)
fromInteger x = if even x then Even (fromInteger x) else undefined
The only way to introduce incorrect Even values would be to access the
constructor directly, but in that example, it's not exported. The
interface to constructing Even values is the fromInteger function.
nightmare = unsafePerformIO (getWrongWife >>= sex)
More information about the Beginners