[Haskell-beginners] Searching Maybe lists

Thomas Friedrich info at suud.de
Tue May 19 09:39:16 EDT 2009


Hi Aditya,

Please try the following:

findJust :: (Eq a) => [Maybe a] -> Maybe a
findJust xs = case (dropWhile (==Nothing) xs) of
              [] -> Nothing
              cs -> head cs

yourFunction :: (Eq b) => (a -> Maybe b) -> [a] -> Maybe b
yourFunction f xs = findJust (map f xs)

It only uses functions from the Prelude, and as Haskell evaluates lazy, 
it just does exactly what you wants.

Happy Hacking,
Thomas



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 
> which is undesirable for long lists. How can I fix it?
>
> Curiously, the regular 'Data.List.find' function that applies a 
> Boolean predicate to each member of the list also seems to first 
> traverse the entire list using 'filter' and then grabs the head of the 
> result.
>
> Thanks ...
> -deech
> ------------------------------------------------------------------------
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>   



More information about the Beginners mailing list