never executed always true always false
1 {-# LANGUAGE UndecidableInstances #-}
2 module HelVM.HelIO.Containers.LLIndexSafe where
3
4 import HelVM.HelIO.Control.Safe
5
6 import Data.ListLike hiding (show)
7
8 import Prelude hiding (break, divMod, drop, fromList, length, splitAt, swap, uncons)
9
10 -- | Index
11 naturalIndexSafe :: (MonadSafe m , IndexSafe full item) => full -> Natural -> m item
12 naturalIndexSafe l = indexSafe l <$> fromIntegral
13
14 -- | Type Class
15 class IndexSafe full item | full -> item where
16 indexSafe :: MonadSafe m => full -> Int -> m item
17 indexSafe l = liftMaybeOrError "LLTIndexSafe.indexSafe:" . indexMaybe l
18
19 indexMaybe :: full -> Int -> Maybe item
20 indexMaybe l = rightToMaybe <$> indexSafe l
21
22 atSafe :: MonadSafe m => Int -> full -> m item
23 atSafe = flip indexSafe
24
25 atMaybe :: Int -> full -> Maybe item
26 atMaybe = flip indexMaybe
27
28 atWithDefault :: item -> Int -> full -> item
29 atWithDefault e i = fromMaybe e <$> findMaybe i
30
31 findSafe :: MonadSafe m => Int -> full -> m item
32 findSafe = atSafe
33
34 findMaybe :: Int -> full -> Maybe item
35 findMaybe = atMaybe
36
37 findWithDefault :: item -> Int -> full -> item
38 findWithDefault = atWithDefault
39
40 {-# DEPRECATED findSafe "Use `atSafe`" #-}
41 {-# DEPRECATED findMaybe "Use `atMaybe`" #-}
42 {-# DEPRECATED findWithDefault "Use `atWithDefault`" #-}
43
44 instance ListLike full item => IndexSafe full item where
45 indexSafe = indexSafeLL
46
47 -- | Internal functions
48 indexSafeLL :: (MonadSafe m , ListLike full item) => full -> Int -> m item
49 indexSafeLL l i
50 | i < 0 = liftErrorWithTupleList "LLIndexSafe.indexSafeLL: index must be >= 0" [("i" , show i)]
51 | ll <= i = liftErrorWithTupleList "LLIndexSafe.indexSafeLL: index must not found" [("i" , show i) , ("length l" , show ll)]
52 | otherwise = (pure <$> index l) i
53 where ll = length l