[Haskell-beginners] cascade of if statements
Daniel Trstenjak
daniel.trstenjak at gmail.com
Wed Oct 31 18:14:52 CET 2012
Hi Emmanuel,
you could write monadic boolean operators (<&&>, <||>) and a "monadic"
when (whenM) - I think both are in some package - to be able to write somwthing like:
whenM (not <$> doesFileExist file <||> olderThan twoHours file) $ do
...
import Control.Applicative ((<$>))
(<&&>) :: Monad m => m Bool -> m Bool -> m Bool
(<&&>) m1 m2 = do
r1 <- m1
if r1 then m2 else return False
(<||>) :: Monad m => m Bool -> m Bool -> m Bool
(<||>) m1 m2 = do
r1 <- m1
if r1 then return True else m2
whenM :: Monad m => m Bool -> m () -> m ()
whenM p m = do
r <- p
if r then m else return ()
olderThan :: Int -> FilePath -> IO Bool
olderThan secs file = do
modif <- getModificationTime file
curTime <- getClockTime
let diff = diffClockTimes curTime modif
return $ tdSec diff >= secs
twoHours = 3600 * 2
'not <$> doesFileExist file' is a shorcut for:
r <- doesFileExist file
return $ not r
But all of this would mostly only really pay off, if you have some file
operations heavy code. Otherwise, all of these helper functions (operators) are quite generic.
Obviously, I'm currently a bit bored ...
Greetings,
Daniel
More information about the Beginners
mailing list