stusmith
stusmith

Reputation: 14103

What's the alternative to exceptions in a deep Haskell recursion?

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.

Upvotes: 6

Views: 481

Answers (2)

user395760
user395760

Reputation:

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 be Right theParseTree or Left 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.

Upvotes: 5

Paul
Paul

Reputation: 2238

Haskell provides the Maybe and Either types for this. Since you want to return an error state, Either seems to be what you want.

Upvotes: 9

Related Questions