What should be the result type of this function?

I want to write a function saveStuffthat saves something to a file after passing certain tests. If the tests fail, I need to raise an error. What should be the result type of this function? I thought about IO (Either String ())and IO (Maybe String), but for some reason they feel wrong. I searched for similar functions from the standard library, but they just return IO (). They throw exceptions for failures. I can’t find myself such an approach.

+5
source share
2 answers

You can write something that returns ErrorT String IO (). Documentation for Monad Transformer ErrorT in Hackage . The excellent Eight Ways to Report Errors has more suggestions from Eric Kidd and the next few years later by Edward Ian.

+7
source

If only one method saveStuffcan be successful, then a type that is isomorphic Maybe ErrorMessageis the right type. Maybe ErrorMessageItself has a flaw, which usually Nothingmeans a failure to use Maybe, so it will contradict the expectations here. As for this, Either ErrorMessage ()it is better, but the parameter ()for the case Rightdoes not carry any information, so this parameter also does not have elegance.

If you do not want to accept these shortcomings, define your own type of result

data Result = Success | Failure ErrorMessage
-- with type ErrorMessage = String, for example
+6
source

All Articles