I wonder what are the advantages of Maybe monad over exceptions? It looks like Maybe is just explicit (and rather space-consuming) way of try..catch syntax.
update Please note that I'm intentionally not mentioning Haskell.
|
I wonder what are the advantages of update Please note that I'm intentionally not mentioning Haskell. |
||||
|
|
|
Using So a function like So what are the advantages of the First, let's say you want to try several functions that could error out in a row until you get one that doesn't. If you don't get any without errors, you want to return a special error message. This is actually a very useful pattern but would be a horrible pain using
Another example is having an optional function. Let's say you have several functions to run, including one that tries to optimize a query. If this fails, you want everything else to run anyhow. You could write code something like:
Both of these cases are clearer and shorter than using Also note that you do not have to litter your code with lines like Finally, another advantage is that a Another win is that That said, there are some caveats. For one, neither Another problem is having multiple types of errors return (this only applies to Still, over all, I prefer the |
|||
|
|
|
|||||||||||||||||||||
|
|
"Maybe" is not a replacement for exceptions. Exceptions are meant to be used in exceptional cases (for instance: opening a db connection and the db server is not there although it should be). "Maybe" is for modeling a situation when you may or may not have a valid value; say you are getting a value from a dictionary for a key: it may be there or may be not - there is nothing "exceptional" about any of these outcomes. |
|||||||
|
|
The maybe monad is basically the same as most mainstream language's use of "null means error" checking (except it requires the null to be checked), and has largely the same advantages and disadvantages. |
|||||||||||||||||
|
|
The Haskell type system will require the user to acknowledge the possibility of a |
|||||||||||||||||||
|