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

Lennart Augustsson lennart at augustsson.net
Tue Feb 23 15:08:32 EST 2010


If you use read (reads) and show for the actual conversion it will round trip.
It appears to be non-trivial since most languages and libraries get it wrong. :)

  -- Lennart

On Tue, Feb 23, 2010 at 1:44 PM, Andy Gimblett <haskell at gimbo.org.uk> wrote:
> Hi all,
>
> Short version: How can I pretty print and parse values of type Double such
> that those operations are each other's inverse?
>
> 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