[Haskell-beginners] Searching Maybe lists
aditya siram
aditya.siram at gmail.com
Mon May 18 22:56:00 EDT 2009
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090518/067465a8/attachment.html
More information about the Beginners
mailing list