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

Libor Wagner liborwagner at gmail.com
Tue Jan 29 11:30:38 CET 2013


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





More information about the Beginners mailing list