[Haskell-cafe] Doubting Haskell

Robert Dockins robdockins at fastmail.fm
Sat Feb 16 18:40:58 EST 2008


I'm going to try to respond the the main practical question in this message; 
perhaps others will feel up to addressing the more philosophical aspects.

(I see now that Cale has beaten me to the punch, but I guess I'll post this 
anyways...)

> Greetings Haskellers,
[snip quite a bit of discussion]

> Great. Next, translate the bit that
> says (pseudocode):
>
>   if(attempt_file_open)
>     if(attempt_file_read)
>       process
>
> That's it. No fancy, complex error messages. Just check the error
> returns and only proceed if I have something to proceed with. Like
> grown-ups do. I *will* check my error returns. I have tormented too
> many newbies to *ever* consider doing anything else. If I cannot check
> my error returns I will not write the program.

You'll find in Haskell that the normal way of handling things like I/O errors 
is to use the exception handling mechanism.  There aren't usually "error 
returns" to check.  Instead you usually place error handlers at the positions 
where you want to be notified of errors using the "catch" or "handle" 
functions.  If you want to you can convert any IO action into one with an 
error return by using the "try" function.  The Control.Exception module is 
probably the one you want to check out.

http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Exception.html

[snip more discussion]

> If so, 
> I sincerely suggest an example or two, like the small but well formed
> programs in K&R, Stroustrup or Gosling saying things like:
>
>   if((fp = fopen(...)) != NULL)
>   {
>     if(fgets(...) != NULL)
>     {
>       printf(...);
>     }
>
>     fclose(...)
>   }

Here is a quick example I whipped up.  It includes both a pretty direct 
translation of the above code, and another version which is a little more 
idiomatic.

Rob Dockins

----------- code follows ----------------
import Control.Exception
import System.IO


main = direct_translation

direct_translation = do
  tryh <- try (openFile "test.txt" ReadMode)
  case tryh of
    Left err -> print err
    Right h -> do
       tryl <- try (hGetLine h)
       case tryl of
         Left err -> do print err; hClose h
         Right l -> do
             putStrLn l
             hClose h
      
the_way_I_would_do_it = handle (\err -> print err) $
  bracket (openFile "test.txt" ReadMode) hClose $ \h -> do
     l <- hGetLine h
     putStrLn l


More information about the Haskell-Cafe mailing list