Haskell index list exception throwing

getChar :: Int -> IO Char
getChar n = do   
    c <- getLine   
    return (c !! n)   

The program should have a number and a string, and it will return a char, but how can I catch an exception if the number is too large?

I tried like this, but it doesn't seem to work

getChar n   
   = do    
       c <-getLine   
| n>=0 && n < b   
  = return c !! n    
| otherwise    
  = error "Too big number"    
where
  b = length c

This is not homework, I'm trying to get myself involved. Google didint gave me helpful answers.
Could not implement catch. Examples?

+3
source share
3 answers

You will probably want to rebuild the structure a bit, as you have an IO involved in something that shouldn't be. How about changing the signature to something like this?

getChar :: Int -> String -> Maybe Char
getChar n x | n < length x = Just (x !! n)
            | otherwise = Nothing

Data.Maybe , - (, ) Nothing ( ). , getChar, , . Data.Either . , ( ), Haskell , , Either Maybe, .

, , , , , .

main :: IO ()
main = do
  x <- getLine
  let z = getChar' 5 x
  case z of
      (Just z) -> print $ "The 5th character is " ++ show z
      Nothing -> print $ "The 5th character is out of range"
+8

drop, n (drop , n), listToMaybe - a ( Just c, c - , Nothing, ):

import Data.Maybe (listToMaybe)

getchar :: Int -> IO (Maybe Char)
getchar n = do
    line <- getLine
    return . listToMaybe . drop n $ line
+2
getChar' :: Int -> IO Char
getChar' n = 
    do
            c <- getLine
            if (n < length c)
               then
                    return (c !! n)
               else
                    getChar' n

You can do something like above. This is just an example. But, since you are a beginner, it is highly recommended not to play with IO and Monads. You can come to it after familiarizing yourself with purely functional concepts.

+1
source

All Articles