I'm writing a simple recursive descent parser in OCaml. Typically (as far as I can tell from the tutorials online and in books), exceptions are used to indicate parse failures, for example:
match tok with
TokPlus -> ...
| _ -> raise SyntaxError
However, I'm thinking of using the option type instead, i.e.:
match tok with
TokPlus -> Some(...)
| _ -> None
The main reason I want to do this is that using option types allows me to optimize some of my combinators to be tail-recursive.
Are there any shortcomings with using options instead of exceptions? Will this decision bite me in the foot as I start parsing more complex structures?
I believe exceptions optimize the common case - the code path for successful parse is simpler. Usually when parsing it is all or nothing - either everything parses ok and you return the final result or something breaks - and you don't care where it breaks because you are not going to handle it anyway, except to print meaningful message, but one can skip that step too :) So looks like a perfect match for exceptions.