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

I am trying to learn Haskell by writing small programs ... so now I am writing lexer / parser for simple expressions. (Yes, I could use Alex / Happy ... but first I want to learn the main language).

My parser is essentially a set of recursive functions that build a tree. In the case of syntax errors, I would usually throw an exception (i.e., If I wrote in C #), but in Haskell this did not seem to be encouraging.

So what is the alternative? I do not want to check the error states in each individual fragment of the analyzer. I want to either get the correct tree of nodes, or an error state with details.

+6
exception-handling recursion haskell
source share
2 answers

For a calculation that may fail with details about why it fails, there is type Either ab , for example. Either ErrorDetails ParseTree , so your result could be Right theParseTree or Left ErrorDetails . You can map patterns to these constructors in your recursive function, and if there is an error, you pass it; otherwise you continue as usual.

+5
source share

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

+9
source share

All Articles