Send Beginners mailing list submissions to
[email protected]
To subscribe or unsubscribe via the World Wide Web, visit
http://www.haskell.org/mailman/listinfo/beginners
or, via email, send a message with subject or body 'help' to
[email protected]
You can reach the person managing the list at
[email protected]
When replying, please edit your Subject line so it is more specific
than "Re: Contents of Beginners digest..."
Today's Topics:
1. Get resource from number of possible sources (Libor Wagner)
----------------------------------------------------------------------
Message: 1
Date: Tue, 29 Jan 2013 11:30:38 +0100
From: Libor Wagner <[email protected]>
Subject: [Haskell-beginners] Get resource from number of possible
sources
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="utf-8"
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
[email protected]
http://www.haskell.org/mailman/listinfo/beginners
End of Beginners Digest, Vol 55, Issue 34
*****************************************