Sukit Tretriluxana:
> I was looking around Stroustrup's website and found
> a simple program... I wondered how a Haskell
> program equivalent to it looks like...

> main = E.catch (interact reverseDouble) (\_ -> print "format error")
>          toDoubles = map (read::String->Double)

For a "safe" program in Haskell, we would not normally use
an unsafe function like "read", and then try to rescue it by
catching IO exceptions. Instead, we would write the program
safely to begin with. Something like this (building on
Jonathan's idea):

import Data.Maybe (listToMaybe)

main = interact reverseDouble

reverseDouble =
  unlines . intro .
  maybe ["format error"] (map show . reverse) .
  mapM (readMaybe :: String -> Maybe Double) .
  takeWhile (/= "end") . words
   where
     intro l =
       ("read " ++ show (length l) ++ " elements") :
       "elements in reversed order" :
       l

readMaybe :: Read a => String -> Maybe a
readMaybe = listToMaybe . map fst . reads

The function "readMaybe" returns the pure value
"Nothing" if there is a format error instead of throwing
an IO exception. It has been proposed to make it part
of the standard libraries - I'm not sure what the status
is of that process.

Regards,
Yitz
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to