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

Ertugrul Soeylemez es at ertes.de
Sun Dec 28 10:26:10 EST 2008


Colin Paul Adams <colin at colina.demon.co.uk> wrote:

> I want to declare a type thus:
>
> type Coordinate = (Int, Int)
>
> But the two integers must be confined to the inclusive range 0-11. Can
> i express that in the type system?

Well, the type system allows you to create your own ranged integer type.
Here is a rather inflexible, but working method to do it:

  newtype Int12 = Int12 Int
    deriving (Eq, Read, Show)

  instance Num Int12 where
    Int12 x + Int12 y
      | x+y <= 11 = Int12 (x+y)
      | otherwise = error "Int12 addition out of range"
    ...


Greets,
Ertugrul.


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://blog.ertes.de/




More information about the Beginners mailing list