Haskell 错误处理问题

Haskell error handling issue

我有这段代码

expand :: Expression -> [String] -> Context -> Expression

expand expr [] context = expr

expand expr (x:xs) context = expand (subst x newExp expr) xs context
    where 
        (Just newExp) = (M.lookup x context)

如果 (M.lookup x context) 为 Nothing,我正在尝试抛出错误,是否可以这样做?

谢谢!

就让expandreturnMaybe Expression:

expand expr [] context = Just expr
expand expr (x:xs) context = do
    newExpr <- M.lookup x context
    expand (subst x newExpr expr) xs context

这就是 Maybe 的用途,而不是使用 error 抛出错误,您可以 return 一个值,稍后再决定如何报告该错误给用户。我们的想法是使用一种可以指示成功或失败的数据类型,而不是让您的程序崩溃。

如果你真的非常想用error代替,你可以写

expand expr [] context = expr
expand expr (x:xs) context = case M.lookup x context of
    Nothing -> error $ x ++ " not found in context"
    Just newExpr -> expand (subst x newExp expr) xs context

但请注意,这绝对不是惯用的 Haskell,最好进行适当的错误处理,尤其是当 Maybe 的 monad 实例使它变得如此简单时。