[Haskell-beginners] Re: Restricting integers in a type?
Colin Paul Adams
colin at colina.demon.co.uk
Sun Dec 28 10:56:14 EST 2008
>>>>> "Ertugrul" == Ertugrul Soeylemez <es at ertes.de> writes:
Ertugrul> 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?
Ertugrul> Well, the type system allows you to create your own
Ertugrul> ranged integer type. Here is a rather inflexible, but
Ertugrul> working method to do it:
Ertugrul> newtype Int12 = Int12 Int deriving (Eq, Read, Show)
Ertugrul> instance Num Int12 where Int12 x + Int12 y | x+y <= 11
Ertugrul> = Int12 (x+y) | otherwise = error "Int12 addition out of
Ertugrul> range" ...
That would seem to allow x = -3 and y = 13, for instance.
--
Colin Adams
Preston Lancashire
More information about the Beginners
mailing list