在Haskell中索引列表时捕获异常

Stu*_*ent 3 haskell exception list

getChar :: Int -> IO Char
getChar n = do   
    c <- getLine   
    return (c !! n)   
Run Code Online (Sandbox Code Playgroud)

该程序必须需要一个数字和一行,它将返回char,但如果数字太大,我如何捕获异常?

我试过这样但它似乎没有用

getChar n   
   = do    
       c <-getLine   
| n>=0 && n < b   
  = return c !! n    
| otherwise    
  = error "Too big number"    
where
  b = length c
Run Code Online (Sandbox Code Playgroud)

这不是一个功课,我试图让自己参与其中.谷歌didint给我有用的答案
无法在那里实现捕获.例子?

Jef*_*ter 8

你可能想要重新构建一些东西,因为你已经把IO混合在一起它不必要的东西.将签名更改为这样的内容怎么样?

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

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"
Run Code Online (Sandbox Code Playgroud)