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.
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@haskell.org
http://www.haskell.org/mailman/listinfo/beginners