Ix and a few typos
[haskell-report.git] / libraries / code / Ix.hs
1 module Ix ( Ix(range, index, inRange), rangeSize ) where
2
3 class 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
8
9 rangeSize b@(l,h) | null (range b) = 0
10 | otherwise = index b h + 1
11 -- NB: replacing "null (range b)" by "l > h" fails if
12 -- the bounds are tuples. For example,
13 -- (2,1) > (1,2),
14 -- but
15 -- range ((2,1),(1,2)) = []
16
17
18 instance Ix Char where
19 range (m,n) = [m..n]
20 index b@(c,c') ci
21 | inRange b ci = fromEnum ci - fromEnum c
22 | otherwise = error "Ix.index: Index out of range."
23 inRange (c,c') i = c <= i && i <= c'
24
25 instance Ix Int where
26 range (m,n) = [m..n]
27 index b@(m,n) i
28 | inRange b i = i - m
29 | otherwise = error "Ix.index: Index out of range."
30 inRange (m,n) i = m <= i && i <= n
31
32 instance Ix Integer where
33 range (m,n) = [m..n]
34 index b@(m,n) i
35 | inRange b i = fromInteger (i - m)
36 | otherwise = error "Ix.index: Index out of range."
37 inRange (m,n) i = m <= i && i <= n
38
39 instance (Ix a,Ix b) => Ix (a, b) -- as derived, for all tuples
40 instance Ix Bool -- as derived
41 instance Ix Ordering -- as derived
42 instance Ix () -- as derived