1 module Ix ( Ix(range, index, inRange, rangeSize) ) where
3 class Ord a => Ix a where
4 range :: (a,a) -> [a]
5 index :: (a,a) -> a -> Int
6 inRange :: (a,a) -> a -> Bool
7 rangeSize :: (a,a) -> Int
9 rangeSize b@(l,h) | null (range b) = 0
10 | otherwise = index b h + 1
11 -- NB: replacing "null (range b)" by "not (l <= h)"
12 -- fails if the bounds are tuples. For example,
13 -- (1,2) <= (2,1)
14 -- but the range is nevertheless empty
15 -- range ((1,2),(2,1)) = []
17 instance Ix Char where
18 range (m,n) = [m..n]
19 index b@(c,c') ci
21 | otherwise = error "Ix.index: Index out of range."
22 inRange (c,c') i = c <= i && i <= c'
24 instance Ix Int where
25 range (m,n) = [m..n]
26 index b@(m,n) i
27 | inRange b i = i - m
28 | otherwise = error "Ix.index: Index out of range."
29 inRange (m,n) i = m <= i && i <= n
31 instance Ix Integer where
32 range (m,n) = [m..n]
33 index b@(m,n) i
34 | inRange b i = fromInteger (i - m)
35 | otherwise = error "Ix.index: Index out of range."
36 inRange (m,n) i = m <= i && i <= n
38 instance (Ix a,Ix b) => Ix (a, b) -- as derived, for all tuples
39 instance Ix Bool -- as derived
40 instance Ix Ordering -- as derived
41 instance Ix () -- as derived