Skip to content

Pretty printing #73

Description

@LSLeary

I need to present polynomials to users with particular variable names in as clean a form as possible, as such, I've written and am using ppPoly:

ppPoly :: UPoly Double -> Text -> Text
ppPoly p var = fold $ go (U.length coeffs - 1)
 where
  coeffs = unPoly p
  go -1 = []
  go  n = ppSign n (signum coeff)
       <> ppDouble 'g' 1 (abs coeff)
       <> ppPower (" " <> var) n
        : go (n - 1)
   where
    coeff = coeffs U.! n
    ppSign m x
      | m == U.length coeffs - 1 = if x < 0 then  "-"  else ""
      | otherwise                = if x < 0 then " - " else " + "
    ppPower _    0 = ""
    ppPower base 1 = base
    ppPower base k = base <> "^" <> pack (show k)

ppDouble :: Char -> Int -> Double -> Text
ppDouble c n x = pack (printf ("%.*" ++ [c]) n x)

It's one of the building blocks I intend to expose, but ideally pretty printing would move into (and be provided by) poly instead.
I don't have any intention to make a PR at this point in time, but anyone who wants to do so is free to adapt the above.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions