这是error
为了什么。从文档中:
error :: [Char] -> a
error
停止执行并显示错误消息。
例如:
zsh% runhaskell <<<'main = putStrLn (error "Message") >> print "Not reached."'
runghcXXXX7729.hs: Message
The effect of putStrLn
is ignored, and the program terminates as soon as the value produced by error
is demanded (lazy evaluation means that just putting error
somewhere doesn't immediately cause an error; as you might or might not expect, let x = error "Message" in putStrLn "Printed"
causes no errors). It is possible to catch these exceptions with the functions from Control.Exception.Base
, such as catch
, but I've never done this nor have I seen this done.
Also, as a final note, consider avoiding the use of error
. Partial functions (functions that aren't defined over their entire input domain) are best avoided when possible, as it's much easier to reason about your code with the stronger guarantees total functions provide. It's nice when, as for total functions, f :: A -> B
really means "the function f
returns something of type B
"; for partial functions, f :: A -> B
means only "if the function f
returns, then what it returns is of type B
". In your case, this might mean having a type like interpretExpr :: Vars -> Expr -> Either RuntimeError Val
, or something suitably isomorphic (in the simplest case, perhaps data Result = Error String | Value Val
, and interpretExpr :: Vars -> Expr -> Result
).