Skip to content

Commit

Permalink
Surrounds negative numbers with parentheses when necessary
Browse files Browse the repository at this point in the history
This behavior is consistent with Show instances of integral types in
base and allows the result of `show` to be parsed as Haskell code.
The added test used to fail and now passes:

```
    show (Just (-1)):                   FAIL
      test/test.hs:116:
      expected: "Just (-1.0)"
       but got: "Just -1.0"
```
  • Loading branch information
watashi committed Jul 8, 2019
1 parent b4eb458 commit acf8b35
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
3 changes: 3 additions & 0 deletions changelog
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@

* Make / on Scientifics slightly more efficient.

* Fix the Show instance to surround negative numbers with parentheses when
necessary.

0.3.6.2
* Due to a regression introduced in 0.3.4.14 the RealFrac methods
and floatingOrInteger became vulnerable to a space blowup when
Expand Down
13 changes: 9 additions & 4 deletions src/Data/Scientific/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -953,11 +953,16 @@ isE c = c == 'e' || c == 'E'

-- | See 'formatScientific' if you need more control over the rendering.
instance Show Scientific where
show s | coefficient s < 0 = '-':showPositive (-s)
| otherwise = showPositive s
showsPrec d s
| coefficient s < 0 = showParen (d > prefixMinusPrec) $
showChar '-' . showPositive (-s)
| otherwise = showPositive s
where
showPositive :: Scientific -> String
showPositive = fmtAsGeneric . toDecimalDigits
prefixMinusPrec :: Int
prefixMinusPrec = 6

showPositive :: Scientific -> ShowS
showPositive = showString . fmtAsGeneric . toDecimalDigits

fmtAsGeneric :: ([Int], Int) -> String
fmtAsGeneric x@(_is, e)
Expand Down
6 changes: 6 additions & 0 deletions test/test.hs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ main = testMain $ testGroup "scientific"

, testGroup "Formatting"
[ testProperty "read . show == id" $ \s -> read (show s) === s
, testCase "show (Just 1)" $ testShow (Just 1) "Just 1.0"
, testCase "show (Just 0)" $ testShow (Just 0) "Just 0.0"
, testCase "show (Just (-1))" $ testShow (Just (-1)) "Just (-1.0)"

, testGroup "toDecimalDigits"
[ smallQuick "laws"
Expand Down Expand Up @@ -283,6 +286,9 @@ testReads inp out = reads inp @?= out
testRead :: String -> Scientific -> Assertion
testRead inp out = read inp @?= out

testShow :: Maybe Scientific -> String -> Assertion
testShow inp out = show inp @?= out

testScientificP :: String -> [(Scientific, String)] -> Assertion
testScientificP inp out = readP_to_S Scientific.scientificP inp @?= out

Expand Down

0 comments on commit acf8b35

Please sign in to comment.