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.
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 theParseTreeorLeft 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.