Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ new ] utility for pretty printing Doubles #31

Merged
merged 1 commit into from
Apr 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/Text/Show/Pretty.idr
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module Text.Show.Pretty

import Data.List
import Data.List1
import Text.PrettyPrint.Bernardy

import public Text.Show.Value
Expand All @@ -13,6 +14,35 @@ import public Text.Show.PrettyVal.Derive
-- Utilities
--------------------------------------------------------------------------------

dropTrailingZeros : SnocList Char -> String
dropTrailingZeros [<] = "0"
dropTrailingZeros [<'.'] = "0"
dropTrailingZeros (i :< '.') = fastPack (i <>> [])
dropTrailingZeros (i :< '0') = dropTrailingZeros i
dropTrailingZeros sc = fastPack (sc <>> [])

roundUp : SnocList Char -> String
roundUp [<] = "1"
roundUp [<'.'] = "1"
roundUp (i :< '.') = show $ cast {to = Integer} (fastPack (i <>> [])) + 1
roundUp (i :< '9') = roundUp i
roundUp (i :< c) = fastPack (i <>> [chr $ ord c + 1])

||| Prints a floating point number with at most the given number
||| of digits after the dot.
export
printDouble : (precision : Nat) -> Double -> String
printDouble prec v =
case forget $ split ('.' ==) (fastUnpack $ show v) of
[x,y] =>
case splitAt prec y of
(pre,[]) => dropTrailingZeros ([<] <>< (x ++ '.' :: pre))
(pre,c::_) =>
if c <= '4'
then dropTrailingZeros ([<] <>< (x ++ '.' :: pre))
else roundUp ([<] <>< (x ++ '.' :: pre))
_ => show v

-- Don't put parenthesis around constructors in infix chains
isInfixAtom : Value -> Bool
isInfixAtom (InfixCons _ _) = False
Expand Down
Loading