[论文解读] Exceptionally Monadic Error Handling
本文引入了一种名为'连结单子'(conjoined monads)的新型单子结构,通过在双索引单子中将错误视为一等值,统一了错误处理与计算。作者指出,Haskell 的 'catch' 操作符的类型与语义是单子绑定(monadic bind)的特例,由此表明:以错误类型和结果类型为索引的计算,自然地以两种方式形成单子,从而为错误处理、解析器组合子以及通过延续传递风格实现的异常提供统一且可组合的类型安全基础。
We notice that the type of catch :: c a -> (e -> c a) -> c a operator is a special case of monadic bind operator (>>=) :: m a -> (a -> m b) -> m b, the semantics (surprisingly) matches, and this observation has many interesting consequences. For instance, the reader is probably aware that the monadic essence of the (>>=) operator of the error monad $λA.E \lor A$ is to behave like identity monad for "normal" values and to stop on "errors". The unappreciated fact is that handling of said "errors" with a catch operator of the "flipped" "conjoined" error monad $λE.E \lor A$ is, too, a monadic computation that treats still unhandled "errors" as "normal" values and stops when an "error" is finally handled. We show that for an appropriately indexed type of computations such a "conjoined" structure naturally follows from the conventional operational semantics of throw and catch operators. Consequently, we show that this structure uniformly generalizes all conventional monadic error handling mechanisms we are aware of. We also demonstrate several more interesting instances of this structure of which at least bi-indexed monadic parser combinators and conventional exceptions implemented via continuations have immediate practical applications. Finally, we notice that these observations provide surprising perspectives on error handling in general and point to a largely unexplored trail in programming language design space.
研究动机与目标
- 在单一代数结构下统一函数式编程中多样的错误处理机制。
- 证明 'catch' 操作符的类型与语义是单子绑定的特例,揭示单子计算中更深层的对偶性。
- 表明以错误类型和结果类型为双索引的单子(bi-indexed monads)自然支持纯计算与错误处理作为一等单子操作。
- 为模块化、可组合且类型安全的错误处理提供基础,该基础可泛化现有机制如 MonadError、ExceptT 和传统异常。
- 倡导编程语言设计应原生支持此结构,以避免当前单子错误处理在语法和组合性上的缺陷。
提出的方法
- 定义双索引类型构造器 'c e a',其中 'e' 表示错误类型,'a' 表示结果类型,并证明其在两个索引上均形成单子。
- 通过统一操作语义方程中的类型,证明 'catch' 操作符具有单子错误处理的最通用类型。
- 证明 'throw' 是绑定操作的左零元,'return' 是 'catch' 的左零元,从而建立代数对偶性。
- 展示标准单子如 'Either'、'ExceptT' 和带异常的 'IO' 均为此连结单子结构的实例。
- 构造新实例,如双索引解析器组合子,以及通过二阶类型 'callCC' 和 'ThrowT' 变换器实现的传统异常。
- 使用 Scott 编码和延续传递风格,将传统异常建模为单子计算,从而实现完全的可组合性。
实验结果
研究问题
- RQ1Haskell 中的 'catch' 操作符能否被形式化地理解为单子绑定的特例?其代数后果是什么?
- RQ2满足传统操作语义的单子错误处理操作符,其最通用类型是什么?
- RQ3如何将单子错误处理在不同计算效应(包括解析和异常)之间实现统一泛化?
- RQ4通过延续实现的传统异常能否被表达为一种可与其它单子自然组合的单子结构?
- RQ5这种对偶性对编程语言设计有何影响,特别是在避免语法与组合性不一致方面?
主要发现
- 'catch' 操作符的类型是单子绑定的特例,其语义与单子绑定操作完全一致,揭示了更深层的对偶性。
- 双索引类型 'c e a' 在错误索引 'e' 和结果索引 'a' 上均形成单子,从而为正常状态与错误状态提供双重单子行为。
- 'throw' 操作符是绑定操作的左零元,'return' 是 'catch' 的左零元,建立了对称的代数结构。
- 'ExceptT' 单子变换器和带异常的 'IO' 均为此连结单子结构的实例,显示出其广泛适用性。
- 解析器组合子可被定义为连结单子,能精确表达错误类型,并复用标准单子组合子进行错误处理。
- 通过 'callCC' 实现的传统异常可被建模为连结单子,为异常提供一种新颖且实用的单子值编码方式。
阅读本论文
在 Nubint 阅读器中打开原文,边读边就任意段落提问。
在 Nubint 中阅读本论文本解读由 AI 根据论文原文生成,引用前请核对原文。