Haskell 中的异常如何工作? [英] How do exceptions in Haskell work?

查看:19
本文介绍了Haskell 中的异常如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 GHCi 中:

Prelude> error (error "")
*** Exception: 
Prelude> (error . error) ""
*** Exception: *** Exception: 

为什么第一个不是嵌套异常?

Why isn't the first one a nested exception?

推荐答案

答案是这是不精确异常

当纯代码可以显示为一组 异常值(即 errorundefined 的值,并且明确地不是在IO中生成的那种异常a>),则该语言允许返回该集合的任何值.Haskell 中的异常值更像是浮点代码中的 NaN,而不是命令式语言中基于控制流的异常.

When pure code can be shown to evaluate to a set of exceptional values (i.e. the value of error or undefined, and explicitly not the kind of exceptions generated in IO), then the language permits any value of that set to be returned. Exceptional values in Haskell are more like NaN in floating point code, rather than control-flow based exceptions in imperative languages.

即使是高级 Haskeller 偶尔也会遇到的问题,例如:

An occasional gotcha for even advanced Haskellers is a case such as:

 case x of
   1 -> error "One"
   _ -> error "Not one"

由于代码评估为一组异常,GHC 可以自由选择一个.启用优化后,您很可能会发现这总是评估为不是一个".

Since the code evaluates to a set of exceptions, GHC is free to pick one. With optimizations on, you may well find this always evaluates to "Not one".

我们为什么要这样做?因为否则我们会过度限制语言的评估顺序,例如我们将不得不修复一个确定性的结果:

Why do we do this? Because otherwise we'd overly constrain the evaluation order of the language, e.g. we would have to fix a deterministic result for:

 f (error "a") (error "b")

例如,如果存在错误值,则要求从左到右对其进行评估.非常非 Haskelly!

by for example, requiring that it be evaluated left-to-right if error values are present. Very un-Haskelly!

由于我们不想仅仅为了支持 error 而削弱可以对我们的代码进行的优化,因此解决方案是指定结果是一组非确定性选择异常值:不精确的异常!某种意义上来说,所有的异常都被返回,一个被选中.

Since we don't want to cripple the optimizations that can be done on our code just to support error, the solution is to specify that the result is a non-deterministic choice from the set of exceptional values: imprecise exceptions! In a way, all exceptions are returned, and one is chosen.

通常情况下,您不关心 - 异常就是异常 - 除非您关心异常中的字符串,在这种情况下,使用 error 进行调试非常令人困惑.

Normally, you don't care - an exception is an exception - unless you care about the string inside the exception, in which case using error to debug is highly confusing.

参考文献:不精确异常的语义,Simon佩顿·琼斯、阿拉斯泰尔·里德、托尼·霍尔、西蒙·马洛、弗格斯·亨德森.Proc 编程语言设计和实现 (PLDI'99),亚特兰大.(PDF)

References: A semantics for imprecise exceptions, Simon Peyton Jones, Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson. Proc Programming Languages Design and Implementation (PLDI'99), Atlanta. (PDF)

这篇关于Haskell 中的异常如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆