问题
Is there no standard way to print out values for end-user consumption? Show
is clearly more of a debugging convenience than something that would work for this purpose, given the conventions around its use and the constraint that read (show x) == x
.
For example, isn't there at least a simple package like
class (Show a) => PShow a where
pshow :: a -> String
pshow = show
pprint :: (PShow a) => a -> IO ()
pprint = putStrLn . pshow
where instances do something like
instance PShow MyType where
pshow a = someUserFriendlyStringOf a
Note that I'm not asking for something that provides elaborate pretty printing and formatting functionality (I see several packages that do that) just for a simple abstraction that's widely used that allows for pretty printing. Is there something like this?
回答1:
Note that I'm not asking for something that provides elaborate pretty printing and formatting functionality (I see several packages that do that)
There's a reason for that. The people who wrote those elaborate libraries did so because they couldn't get the job done with something simple. You've already hinted at some of the complexity by offering two different methods that may our may not do the same thing, with no guidance about which to use when.
On the positive side, I wouldn't worry too much about read
. Focus on Show
instances that (possibly with GHC extensions) can give you code to cut and paste into your programs.
回答2:
I just did a Hoogle search for a -> String
and found the Language.Haskell.Pretty module.
The module defines three simple functions:
prettyPrintStyleMode :: Pretty a => Style -> PPHsMode -> a -> String
pretty-print with a given style and mode.prettyPrintWithMode :: Pretty a => PPHsMode -> a -> String
pretty-print with the default style and a given mode.prettyPrint :: Pretty a => a -> String
pretty-print with the default style and defaultMode.
The whole typeclass seems to be a bit more complex than what you have asked for, but maybe it helps
来源:https://stackoverflow.com/questions/32532617/is-there-a-pretty-printing-or-showing-abstraction-in-haskell