[Haskell-beginners] Get resource from number of possible sources

David McBride toad3k at gmail.com
Tue Jan 29 16:14:35 CET 2013


You might try

    import Data.Maybe (catMaybes, listToMaybe)
    fmap (listToMaybe . catMaybes) . sequence $ [tryA, tryA', tryA'']

listToMaybe is another word for safeHead or headMay, ie head that returns a
maybe if the list is empty.

or alternatively

    fmap (maybe defaultA id . listToMaybe . catMaybes) . sequence $ [tryA,
tryA', tryA'']

to return a default value if you fail to get A.

On Tue, Jan 29, 2013 at 5:30 AM, Libor Wagner <liborwagner at gmail.com> wrote:

> Hi,
>
> say I have a number of functions tryGetA, tryGetA', tryGetA'' … with the
> type tryGetA :: IO (Maybe A), what I want is to get A, trying these
> function one by one until a get Just a. The first shot code I came up with
> is using if:
>
> getA :: IO A
> getA = do
> a <- tryGetA
> if isJust a
> then return $ fromJust a
> else do
> a' <- tryGetA'
> if isJust a
> then return $ fromJust a'
>>
> there would be some default value at the end, this looks really ugly so I
> have tried another shot:
>
> firstJust :: a -> [Maybe a] -> a
> firstJust a [] = a
> firstJust a (x:xs) = if isJust x
> then fromJust x
> else firstJust a xs
>
> getA :: IO A
> getA = do
> r <- sequence [tryGetA, tryGetA', tryGetA'', …]
> return $ firstJust "OK" r
>
> which is a lot better, but I will appreciate any comment or suggestion.
>
> Thanks,
> Libor
>
>
>
> _______________________________________________
> 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/20130129/0a64a6c8/attachment.htm>


More information about the Beginners mailing list