[Haskell-beginners] Idiomatic way of working with Either and lists

Daniel Fischer daniel.is.fischer at googlemail.com
Sat Jan 26 17:40:49 CET 2013


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



More information about the Beginners mailing list