[Haskell-cafe] Re: Proper round-trip HughesPJ/Parsec for Doubles?

Christian Maeder Christian.Maeder at dfki.de
Tue Feb 23 10:13:22 EST 2010

Andy Gimblett schrieb:
> Hi all,
> Short version: How can I pretty print and parse values of type Double
> such that those operations are each other's inverse?

Maybe you have more luck with show and read (without Parsec.Token).

Your example:
x = 9.91165677454629

fails because the computation performed by the parser
9.0 + 0.91165677454629 yields 9.911656774546291

Cheers Christian

> Long version: I'm writing and QuickCheck-testing a parser using the
> approach set out here:
> http://lstephen.wordpress.com/2007/07/29/parsec-parser-testing-with-quickcheck/
> That is, each syntactic category gets a pretty-printer and a parser and
> an Arbitrary instance, and QuickCheck checks that (parse . prettyPrint)
> == id, basically.  Somewhat unsurprisingly, this sometimes fails for
> floating point values (I'm using Doubles).
> Now, I know that floats are in some sense imprecise, and comparing for
> equality is fraught with peril, but it seems that if x==x then it ought
> to be at least _possible_ to arrange matters such that (parse .
> prettyPrint x) == x as well.  At worst, pretty-printing the underlying
> binary representation!?  So my feeling is that my parser could be improved.
> At the moment I'm working around it by defining a type class which
> checks for equality within some margin of error, and using that instead
> of Eq - but it's messier than I'd like, so I wondered if there was
> something obvious I'm missing.
> As hpaste.org seems to be down, I'll attach a code example here instead.
> Thanks!
> -Andy
> -- 
> Andy Gimblett
> http://gimbo.org.uk/
> ------------------------------------------------------------------------
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

More information about the Haskell-Cafe mailing list