[Haskell-cafe] Nested tests [Code walking off the right edge of the
andrewcoppin at btinternet.com
Sun Jun 21 05:52:22 EDT 2009
Deniz Dogan wrote:
> I (too) often find myself writing code such as this:
> if something
> then putStrLn "howdy there!"
> else if somethingElse
> then putStrLn "howdy ho!"
> else ...
> I recall reading some tutorial about how you can use the Maybe monad
> if your code starts looking like this, but as you can see, that
> doesn't really apply here. "something" and "somethingElse" are simply
> booleans and each of them have different actions to take if either of
> them is True.
> So how do I make code like this prettier?
In a similar vein:
d1x <- doesDirectoryExist d1
f1x <- doesFileExist (d1 </> f1)
d2x <- doesDirectoryExist d2
f2x <- doesFileExist (d2 </> f2)
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."
Obviously, this is nausiating. Surely we can do better somehow?
The above is a simple example. I might need to check file permissions,
invoke external programs, parse files, all sorts of things. And it might
matter which order the tests happen in. Later tests might use
information gained during earlier tests. But the recurring pattern is
"check this thing; if it passes, continue; if it fails, stop here and
emit an error message". Can we abstract this somehow?
More information about the Haskell-Cafe