[Haskell-beginners] Re: Restricting integers in a type?

Colin Paul Adams colin at colina.demon.co.uk
Tue Dec 30 04:15:42 EST 2008


>>>>> "Ertugrul" == Ertugrul Soeylemez <es at ertes.de> writes:

    Ertugrul> 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?

    Ertugrul> Sure:

    Ertugrul>   module Even (Even) where

    Ertugrul>   newtype Even a = Even a deriving (Eq, Show)

    Ertugrul>   instance Integral a => Num (Even a) where Even a +
    Ertugrul> Even b = Even (a+b) -- ...  fromInteger x = if even x
    Ertugrul> then Even (fromInteger x) else undefined

    Ertugrul> The only way to introduce incorrect Even values would be
    Ertugrul> to access the constructor directly, but in that example,
    Ertugrul> it's not exported.  The interface to constructing Even
    Ertugrul> values is the fromInteger function.

Thanks for all your help.
-- 
Colin Adams
Preston Lancashire


More information about the Beginners mailing list