Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failing Fast on IO [String]

Tags:

haskell

Given an IO [String] representing a list of emails:

λ: let emails = return ["[email protected]", "[email protected]"] :: IO [String]

And a function that automatically fails to delete an email:

λ: let deleteEmail email = return $ Left "failed" :: IO (Either String ())

I then looked at how to, for each email in the list, attempt to delete each email. However, when a single email fails to delete, I'd like to stop, i.e. similar to sequence's behavior.

λ: do { e <- emails; _ <- deleteEmail e; return e }
["[email protected]","[email protected]"]

λ: do { e <- emails; result <- deleteEmail e; return result }
Left "failed"

However, from looking at the first do's output, when failing to delete [email protected], the do continues to try to delete [email protected].

How can I modify the above code to fail on the first email deletion failure?

like image 222
Kevin Meredith Avatar asked Apr 07 '26 21:04

Kevin Meredith


1 Answers

There's quite a number of options, but I'd look at three of them, in my order of preference here.

  • Use EitherT transformer over IO instead of IO (Either a) (you'll need to install either package)
  • Use fail from Monad instance of IO.
  • throw an exception.
like image 99
Bartek Banachewicz Avatar answered Apr 10 '26 20:04

Bartek Banachewicz