[Haskell-beginners] Re: Restricting integers in a type?
Ertugrul Soeylemez
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?
Sure:
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.
Greets,
Ertugrul.
--
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://blog.ertes.de/
More information about the Beginners
mailing list