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

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

问题描述

在GHCi中:

 前奏>错误(错误)
***异常:
前奏> (错误错误)
***例外:***例外:

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

解决方案

答案是,这是(有点令人惊讶的)语义不精确的例外



当纯代码可以显示为评估特殊值的时(即错误 undefined ,并明确地这种异常在IO中生成),则该语言允许返回该集合的任何值。 Haskell中的异常值更像是浮点代码中的 NaN ,而不是命令式语言中基于控制流的异常。



<对于甚至是先进的Haskellers来说,偶尔的骗子是一种情况,例如:

  case x of 
1 - >错误One
_ - >错误不是一个

由于代码评估为一组异常,因此GHC可以自由选择一个。通过优化,您可能会发现这总是评估为不是一个。



为什么我们这样做?因为否则我们会过分地约束语言的评估顺序,例如我们必须修正一个确定性的结果:

  f(错误a)(错误b)

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



由于我们不想削弱我们的代码只能支持错误,解决方案是指定结果是从一组异常值中的非确定性选择:不精确的异常!在某种程度上,返回所有异常,并选择一个异常。



通常,你不在乎 - 异常是一个例外 - 除非你关心字符串里面在这种情况下,使用错误来调试是非常困惑的。






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


In GHCi:

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

Why isn't the first one a nested exception?

解决方案

The answer is that this is the (somewhat surprising) semantics of imprecise exceptions

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.

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

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

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")

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

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.

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.


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天全站免登陆