Guest User

Untitled

a guest
Jul 18th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. import Data.List ((!!))
  2. import Control.Monad.Trans.Except
  3. module SafeList where
  4.  
  5. data ListIndexError = ErrIndexTooLarge Int | ErrNegativeIndex
  6. deriving (Eq, Show)
  7.  
  8. infixl 9 !!!
  9.  
  10. isNonEmpty [] = False
  11. isNonEmpty (_:_) = True
  12.  
  13. longerThan :: Int -> [a] -> Bool
  14. longerThan n xs = isNonEmpty $ drop n xs
  15.  
  16. (!!!) :: [a] -> Int -> Except ListIndexError a
  17. (!!!) lst ind | ind < 0 = throwE $ ErrNegativeIndex
  18. | longerThan (ind + 1) lst = return $ lst !! ind
  19. | otherwise = throwE $ ErrIndexTooLarge ind
  20.  
  21. (!!!!) xs n = runExcept $ xs !!! n
  22.  
  23. {-
  24. GHCi> runExcept $ [1..100] !!! 5
  25. Right 6
  26. GHCi> [1,2,3] !!!! 0
  27. Right 1
  28. GHCi> [1,2,3] !!!! 42
  29. Left (ErrIndexTooLarge 42)
  30. GHCi> [1,2,3] !!!! (-3)
  31. Left ErrNegativeIndex
  32. GHCi> [1..] !!!! 0
  33. Right 1
  34. -}
Add Comment
Please, Sign In to add comment