UserPreferences

LibraryDocumentation/Ix


Ix - Library Documentation

Part of the LibraryDocumentation project.

Controls indexing, typically used in conjunction with ?LibraryDocumentation/Array.

module Ix ( Ix(range, index, inRange), rangeSize ) where

class  (Ord a) => Ix a  where
   range               :: (a,a) -> [a]
   index               :: (a,a) -> a -> Int
   inRange             :: (a,a) -> a -> Bool

rangeSize :: Ix a => (a,a) -> Int
rangeSize b@(l,h) | null (range b) = 0
                 | otherwise      = index b h + 1
-- NB: replacing "null (range b)" by "l > h" fails if
-- the bounds are tuples. For example,
-- (2,1) > (1,2),
-- but
-- range ((2,1),(1,2)) = []


instance  Ix Char  where
   range (m,n) = [m..n]
   index b@(c,c') ci
       | inRange b ci  =  fromEnum ci - fromEnum c
       | otherwise     =  error "Ix.index: Index out of range."
   inRange (c,c') i    =  c <= i && i <= c'

instance  Ix Int  where
   range (m,n) = [m..n]
   index b@(m,n) i
       | inRange b i   =  i - m
       | otherwise     =  error "Ix.index: Index out of range."
   inRange (m,n) i     =  m <= i && i <= n

instance  Ix Integer  where
   range (m,n) = [m..n]
   index b@(m,n) i
       | inRange b i   =  fromInteger (i - m)
       | otherwise     =  error "Ix.index: Index out of range."
   inRange (m,n) i     =  m <= i && i <= n

instance (Ix a,Ix b) => Ix (a, b) -- as derived, for all tuples
instance Ix Bool                  -- as derived
instance Ix Ordering              -- as derived
instance Ix ()                    -- as derived

index :: Ix a => (a,a) -> a -> Int

maps a bounding pair, which defines the lower and upper bounds of the range, and a subscript, to an integer.

> index (10,15) 12
2

> index ('A','Z') 'Z'
25

> index ((1,5),(6,10)) (3,7)
14

inRange :: Ix a => (a,a) -> a -> Bool

Returns True if a particular subscript lies in the range defined by a bounding pair.

> inRange (1,5) 3
True

> inRange (1,5) 12
False

> inRange ((1,5),(10,12)) (7,8)
True

range :: Ix a => (a,a) -> [a]

The range operation enumerates all subscripts.

> range (3,6)
[3,4,5,6]

> range ((1,3),(2,4))
[(1,3),(1,4),(2,3),(2,4)]

> range ('e','i')
"efghi"

> range (('a','b'),('c','d'))
[('a','b'),('a','c'),('a','d'),('b','b'),('b','c'),('b','d'),('c','b'),('c','c'),('c','d')]

rangeSize :: Ix a => (a,a) -> Int

TODO