[Haskell-beginners] Selecting single result of function application to list

Daniel Fischer daniel.is.fischer at googlemail.com
Thu Nov 3 17:34:24 CET 2011


On Thursday 03 November 2011, 17:07:01, Hugo Ferreira wrote:
> Hello,
> 
> Apologies the simpleton question but I would like to
> know how it is done in Haskell. I have a list of values,
> and I am applying a function to each of these elements.
> The result is a Maybe. I would like to return the first
> occurrence which is not a Nothing.
> 
> I am considering something like:
> 
> selectOne f = take 1 . filter (\e -> case e of
>                                         Just _ -> True
>                                         _ -> False ) . map f
> 
> I this how it is done?

In Data.Maybe, there's

catMaybes :: [Maybe a] -> [a]
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
listToMaybe :: [a] -> Maybe a
maybeToList :: Maybe a -> [a]

Your selectOne f is 
take 1 . catMaybes . map f
or
take 1 . mapMaybe f

Alternatively, you could use the MonadPlus class from Control.Monad, which 
provides mzero, mplus and msum, with Maybe's MonadPlus instance

selectOne f = maybeToList . msum . map f




More information about the Beginners mailing list