[Haskell-cafe] Haskell and C++ program
Jonathan Cast
jonathanccast at fastmail.fm
Wed Jan 14 17:41:23 EST 2009
On Wed, 2009-01-14 at 12:45 -0800, Sukit Tretriluxana wrote:
> Hi all,
>
> I was looking around Stroustrup's website and found a simple program
> that he showed how standard library can be used to make the program
> succinct and safe. See
> http://www.research.att.com/~bs/bs_faq2.html#simple-program. I
> wondered how a Haskell program equivalent to it looks like and I came
> up with the code below.
>
> import qualified Control.Exception as E
>
> main = E.catch (interact reverseDouble) (\_ -> print "format error")
>
> reverseDouble = unlines . doIt . words
> where doIt = intro . toStrings . reverse . toDoubles . input
> toDoubles = map (read::String->Double)
> toStrings = map show
> input = takeWhile (/= "end")
> intro l = ("read " ++ (show $ length l) ++ " elements") :
> "elements in reversed order" :
My only criticism is that I find code written with lots of secondary
definitions like this confusing; so I would inline most of the
definitions:
reverseDouble =
unlines
. intro
. map show
. reverse
. map (read :: String -> Double)
. takeWhile (/= "end")
. words
where
intro l =
("read " ++ show (length l) ++ " elements") :
"elements in reversed order" :
l
I observe also in passing that the cast on read is somewhat inelegant;
in a real application, the consumer of map read's output would specify
its type sufficiently that the cast would be un-necessary.
For example, the program could be specified to compute sines instead:
main = E.catch (interact unlines . intro . map (show . sin . read) .
words) $ \ _ -> print "format error"
where
intro l =
("read " ++ show (length l) ++ " arguments") :
"computed sins" :
l
(Others will no doubt object to the use of lazy I/O. I disagree in
principle with those objections.)
jcc
PS Stroustrup's comments about vectors are at best half right; push_back
may extend the vector's length correctly, but operator[] on a vector
certainly does not do bounds checking.
More information about the Haskell-Cafe
mailing list