Ix型クラス
Index
Ord型クラスを継承する
Data.Ix
hackage
定義の一部抜粋
code:hs
class (Ord a) => Ix a where
{-# MINIMAL range, (index | unsafeIndex), inRange #-}
range :: (a,a) -> a
index :: (a,a) -> a -> Int
inRange :: (a,a) -> a -> Bool
rangeSize :: (a,a) -> Int
満たすべきlawがある
code:hs
inRange (l,u) i == elem i (range (l,u))
range (l,u) !! index (l,u) i == i, when inRange (l,u) i
map (index (l,u)) (range (l,u))) == 0..rangeSize (l,u)-1
rangeSize (l,u) == length (range (l,u))
range
指定した範囲の全indexのリストを生成
上記のlとuはlower bounds、upper bounds
index
指定された範囲内の特定のindexを対応する整数に変換
inRange
与えられたindexが指定された範囲内にあるかどうか
instanceの定義例
code:hs
instance Ix Char where
{-# INLINE range #-}
range (m,n) = m..n
{-# INLINE unsafeIndex #-}
unsafeIndex (m,_n) i = fromEnum i - fromEnum m
{-# INLINE index #-} -- See Note Out-of-bounds error messages
-- and Note Inlining index
index b i | inRange b i = unsafeIndex b i
| otherwise = indexError b i "Char"
inRange (m,n) i = m <= i && i <= n
使用例
code:hs
import Data.Ix
-- range関数を使って範囲内の全インデックスを生成
indices = range ((1, 1), (3, 3)) -- (1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)
-- inRange関数を使って特定のインデックスが範囲内にあるかをチェック
isInRange = inRange ((1, 1), (3, 3)) (2, 2) -- True