Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Data.List ((!!))
- import Control.Monad.Trans.Except
- module SafeList where
- data ListIndexError = ErrIndexTooLarge Int | ErrNegativeIndex
- deriving (Eq, Show)
- infixl 9 !!!
- isNonEmpty [] = False
- isNonEmpty (_:_) = True
- longerThan :: Int -> [a] -> Bool
- longerThan n xs = isNonEmpty $ drop n xs
- (!!!) :: [a] -> Int -> Except ListIndexError a
- (!!!) lst ind | ind < 0 = throwE $ ErrNegativeIndex
- | longerThan (ind + 1) lst = return $ lst !! ind
- | otherwise = throwE $ ErrIndexTooLarge ind
- (!!!!) xs n = runExcept $ xs !!! n
- {-
- GHCi> runExcept $ [1..100] !!! 5
- Right 6
- GHCi> [1,2,3] !!!! 0
- Right 1
- GHCi> [1,2,3] !!!! 42
- Left (ErrIndexTooLarge 42)
- GHCi> [1,2,3] !!!! (-3)
- Left ErrNegativeIndex
- GHCi> [1..] !!!! 0
- Right 1
- -}
Add Comment
Please, Sign In to add comment