[Haskell-beginners] Searching Maybe lists
aditya siram
aditya.siram at gmail.com
Tue May 19 12:05:09 EDT 2009
Awesome! This seems to be an analog of the Data.List.find function. I
originally didn't implement mine this way because I thought it went through
the entire list, but I was obviously mistaken!
Thanks for your help!
-deech
On Tue, May 19, 2009 at 8:39 AM, Thomas Friedrich <info at suud.de> wrote:
> 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
>>
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090519/7b5b1ad2/attachment-0001.html
More information about the Beginners
mailing list