[Haskell-beginners] Re: Searching Maybe lists

Heinrich Apfelmus apfelmus at quantentunnel.de
Tue May 19 04:05:00 EDT 2009


aditya siram wrote:
> Hi all,
> I would like to define a function that takes a list and a function that
> evaluates each member of the list to a Maybe value and output the first
> element in the list that evaluates to 'Just y', or 'Nothing' once the list
> has been completely processed. So something like:
> 
> findMaybe :: [a] -> (a -> Maybe b) -> Maybe b
> 
> The problem is that I don't want it to go through the entire list, but
> short-circuit when it hits a 'Just ...'. So far I have:
> 
> orMaybe :: Maybe a -> Maybe a -> Maybe a
> orMaybe m1 m2 = case (m1,m2) of
>                   (_, Just a) -> Just a
>                   (Just a, _) -> Just a
>                   _           -> Nothing
> 
> findMaybe :: [a] -> (a -> Maybe b) -> Maybe b
> findMaybe as f = foldr (\a sofar -> sofar `orMaybe` (f a)) Nothing as
>
> 
> 'findMaybe', as far as I can tell, traverses the entire input list

Thanks to lazy evaluation, this is not necessarily the case, see also

   http://en.wikibooks.org/wiki/Haskell/Performance_Introduction#Time


You will have to write  orMaybe  as

   orMaybe Nothing  y = y
   orMaybe x        _ = x

though. (By the way, your original code for  orMaybe  doesn't seem to do
what you want.) This function has already been implemented for you, it's
called

   mplus



Regards,
apfelmus

--
http://apfelmus.nfshost.com



More information about the Beginners mailing list