
On Sat, Jan 26, 2013 at 05:41:39PM +0100, Daniel Fischer wrote:
On Saturday 26 January 2013, 17:26:26, Emmanuel Surleau wrote:
Hi,
I'm trying to figure out the best way to work with Either and lists.
I have a function f which goes:
f :: a -> Either SomeError b
Now, I'd like to do:
applyF :: [a] -> (a -> Either SomeError b) -> Either SomeError [b]
That is, map f over a list and return either a list or the first error found. The function should stop at the first error. I have implemented applyF with a fold, but I'm sure there must be something like this already, being a fairly generic pattern.
Since (Either e) is a Monad,
mapM :: Monad m => (a -> m b) -> [a] -> m [b]
does what you want. If your GHC is <= 7.4.2 (and >= 7.0.1), you will need to
import Control.Monad.Instances
The version with the argument order you gave is
forM :: Monad m => [a] -> (a -> m b) -> m [b] forM = flip mapM
Brilliant. Thank you very much, that's much better than my fold. Cheers, Emm