[Haskell-cafe] Haskell and C++ program

Yitzchak Gale gale at sefer.org
Thu Jan 15 07:12:54 EST 2009


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


More information about the Haskell-Cafe mailing list