[Haskell-cafe] Nested tests [Code walking off the right edge of the screen]

Sebastian Fischer sebf at informatik.uni-kiel.de
Sun Jun 21 08:36:38 EDT 2009


On Jun 21, 2009, at 11:52 AM, Andrew Coppin wrote:

> In a similar vein:
>
> d1x <- doesDirectoryExist d1
> if d1x
>  then do
>    f1x <- doesFileExist (d1 </> f1)
>    if f1x
>      then do
>        d2x <- doesDirectoryExist d2
>        if d2x
>          then do
>            f2x <- doesFileExist (d2 </> f2)
>            if f2x
>              then do_stuff d1 d2 f1 f2
>              else hPutStrLn stderr $ "File " ++ f2 ++ " not found."
>            else hPutStrLn stderr $ "Directory " ++ d2 ++ " not found."
>          else hPutStrLn stderr $ "File " ++ f1 ++ " not found."
>        else hPutStrLn stderr $ "Directory " ++ d1 ++ " not found."

using Control.Monad.Error:

  either (hPutStrLn stderr) return =<< runErrorT $
   do d1x <- lift $ doesDirectoryExist d1
      unless d1x $ fail "Directory " ++ d1 ++ " not found."
      f1x <- lift $ doesFileExist (d1 </> f1)
      unless f1x $ fail "File " ++ f1 ++ " not found."
      d2x <- lift $ doesDirectoryExist d2
      unless d2x $ fail "Directory " ++ d2 ++ " not found."
      f2x <- lift $ doesFileExist (d2 </> f2)
      unless f2x $ fail "File " ++ f2 ++ " not found."
      lift $ doStuff d1 d2 f1 f2

When using

  failUnless boolAction message = lift boolAction >>= (`unless`fail  
message)

the code becomes

  either (hPutStrLn stderr) return =<< runErrorT $
   do failUnless (doesDirectoryExist d1)     $ "Directory " ++ d1 ++ "  
not found."
      failUnless (doesFileExist (d1 </> f1)) $ "File " ++ f1 ++ " not  
found."
      failUnless (doesDirectoryExist d2)     $ "Directory " ++ d2 ++ "  
not found."
      failUnless (doesFileExist (d2 </> f2)) $ "File " ++ f2 ++ " not  
found."
      lift $ doStuff d1 d2 f1 f2

It's similar to Claus's proposal to use MaybeT with additional support  
for error messages.

Sebastian


-- 
Underestimating the novelty of the future is a time-honored tradition.
(D.G.)





More information about the Haskell-Cafe mailing list