[英]Handle exception in haskell
I write the following code: 我编写以下代码:
give :: [b] -> Int -> b
give list index = list !! index
Now I want to add, if the there is no item at point index, it should show: "No item at that position!" 现在我要添加,如果在点索引处没有项目,则应该显示:“该位置没有项目!”
[1..10] `give` 10
No item at that position!
How can I add this in haskell 如何在Haskell中添加此内容
You can't really. 你真的不能。 You can throw exceptions from pure code but you can only catch exceptions in
IO
. 您可以从纯代码中引发异常,但只能在
IO
捕获异常。
You could either reimplement !!
您可以重新实现
!!
in give
to throw an exception more to your liking or just opt for saner error handling, like Either
or Maybe
. give
根据自己的喜好抛出异常,或者只选择更明智的错误处理,例如Either
或Maybe
。
An example of handling errors with Either
might be 使用
Either
处理错误的示例可能是
data OutOfRange = OutOfRange Int
give :: [a] -> Int -> Either OutOfRange a
give xs i | length xs > i = Right $ xs !! i
| otherwise = Left (OutOfRange i)
I would wrap the return type in an Either
monad like this: 我将返回类型包装在
Either
monad中,如下所示:
give :: [b] -> Int -> Either String b
give [] _ = Left "No item at that position!"
give (x:xs) index | index == 0 = Right x
| otherwise = give xs $ index - 1
Either
is a data constructor whose declaration could theoretically look like this: Either
是数据构造函数,其声明理论上可能看起来像这样:
data Either a b = Left a | Right b
Right
and Left
are value constructors for the different types that may be used, in our case, b
and String
. Right
和Left
是可以使用的不同类型的值构造函数,在本例中为b
和String
。
This function returns Either
a String
or a b
depending on whether or not the indexing succeeded. 这个函数返回
Either
一个String
或b
取决于索引是否成功。 It uses pattern matching to fail when indexing into an empty list and uses recursion to eventually emulate !!
当索引到一个空列表时,它使用模式匹配失败,并使用递归最终进行仿真
!!
. 。 Note that due to the strictness of Haskell's type system, you cannot use this result as it were simply of type
b
: you must explicitly handle the possibility of it being a String. 请注意,由于Haskell类型系统的严格性,您不能使用此结果,因为它只是类型
b
:您必须显式处理将其作为String的可能性。 Here is an example: 这是一个例子:
case (give [1..10] 10) of
(Left s) -> putStrLn $ "Error" ++ s --String case
(Right i) -> putStrLn $ "The value you requested is " ++ show $ i --Int case
Using Either
and Maybe
is generally a better idea than signaling errors because it allows your code to gracefully handle error conditions within the Haskell type system with simple pattern matching. 通常,使用
Either
和Maybe
比发信号通知错误是一个更好的主意,因为它允许您的代码通过简单的模式匹配来优雅地处理Haskell类型系统中的错误情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.