实践中出现ErrorT catchError

Joh*_*ler 3 error-handling haskell

我有一个非常典型的设置,在IO monad中有一组可以抛出错误的函数.到目前为止,我刚刚通过模式匹配runErrorT的结果来处理monad链末尾的错误:

replLisp :: LispScope -> String -> IO String
replLisp s input = do
  result <- runErrorT (evalLisp s input)
  return $ either (id) (show) result 
Run Code Online (Sandbox Code Playgroud)

我现在想为我的Hacked小方案添加一些错误处理,但是我很难让类型检查器开心.

如何使用catchError?一两个例子会有所帮助.


这是我最近的尝试:

catch :: [LispVal] -> IOThrowsError LispVal
catch [action rescue] = do
  eval action >>= catchError $ eval rescue
Run Code Online (Sandbox Code Playgroud)

Tho*_*son 7

以下是catchError从先前调用中恢复的示例用法throwError:

import Control.Monad.Error
import Control.Monad.Identity

type MyMonad = ErrorT String Identity
runMyMonad = runIdentity . runErrorT

main = do
        let x = runMyMonad (func 5 0)
        print x

func :: Double -> Double -> MyMonad Double
func w x = do
        y <- (divider x) `catchError` (\_ -> return 1)
        return (w + y)

divider :: Double -> MyMonad Double
divider x = do
        when (x == 0) (throwError "Can not divide by zero!")
        return (10 / x)
Run Code Online (Sandbox Code Playgroud)

尽管传入0了除法,我们可以完成处理程序的结果1以获得输出Right 6.0.

这有帮助吗?你的问题并没有真正说出问题所在.