Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I distinguish negative zero with Aeson?

Haskell distinguishes negative zero:

ghci> (isNegativeZero (0 :: Float), isNegativeZero (-0 :: Float))
(False,True)

JSON also allows for distinguishing them, since both "0" and "-0" are valid, syntactically.

But Aeson throws away the sign bit:

ghci> isNegativeZero <$> eitherDecode "-0"
Right False

Why? How can I decode a JSON document while distinguishing non-negative and negative zero?

like image 233
Janus Troelsen Avatar asked Oct 16 '25 14:10

Janus Troelsen


1 Answers

It looks like in Data.Aeson the floating point number is constructed using Data.Scientific.scientific

scientific :: Integer -> Int -> Scientific

scientific c e constructs a scientific number which corresponds to the Fractional number: fromInteger c * 10 ^^ e.

Since the mantissa is an Integer, where we have 0 == -0, it can not construct a negative zero. Not the best API for constructing special floating point values, it seems.

Perhaps you should file a bug for aeson, asking for a workaround in the parser.

like image 171
chi Avatar answered Oct 19 '25 13:10

chi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!