深度 Haskell 递归中异常的替代方案是什么?
我正在尝试通过编写小程序来学习 Haskell...所以我目前正在为简单表达式编写一个词法分析器/解析器。 (是的,我可以使用 Alex/Happy...但我想先学习核心语言)。
我的解析器本质上是一组构建树的递归函数。在语法错误的情况下,我通常会抛出异常(即,如果我用 C# 编写),但在 Haskell 中似乎不鼓励这样做。
那么还有什么选择呢?我真的不想测试解析器的每一个位中的错误状态。我想要要么得到一个有效的节点树,要么得到一个包含详细信息的错误状态。
I'm trying to learn Haskell by writing little programs... so I'm currently writing a lexer/parser for simple expressions. (Yes I could use Alex/Happy... but I want to learn the core language first).
My parser is essentially a set of recursive functions that build a Tree. In the case of syntax errors, I'd normally throw an exception (i.e. if I were writing in C#), but that seems to be discouraged in Haskell.
So what's the alternative? I don't really want to test for error states in every single bit of the parser. I want to either end up with a valid tree of nodes, or an error state with details.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Haskell为此提供了Maybe和Either类型。由于您想返回错误状态,
Either
似乎就是您想要的。Haskell provides the
Maybe
andEither
types for this. Since you want to return an error state,Either
seems to be what you want.对于可能失败并详细说明失败原因的计算,可以使用
Either a b
类型,例如Either ErrorDetails ParseTree
,因此您的结果可能是Right theParseTree
code> 或左侧错误详细信息
。您可以在递归函数中对这些构造函数进行模式匹配,如果出现错误,则将其传递;否则你就照常进行。For a computation that might fail with details on why it failes, there's the type
Either a b
, e.g.Either ErrorDetails ParseTree
, so your result could beRight theParseTree
orLeft ErrorDetails
. You can pattern-match these constructors in your recursive function and if there's an error, you pass it on; otherwise you go on as usual.