Haskell — easier to read show function? (for debugging)

后端 未结 1 2011
暖寄归人
暖寄归人 2021-02-20 11:19

I\'m looking for a function like show that produces more readable output. It certainly doesn\'t have to work on all classes. I searched \"haskell pretty print\" on Google, but t

1条回答
  •  长情又很酷
    2021-02-20 11:27

    The show function isn't really intended to produce nicely readable output. If you look at the default implementations from the deriving clause and at how the language spec talks about it, it's clear that show and read are intended to serve as a form of simple serialization. Additionally, the serialized format is expected to be parsable as Haskell source such that (assuming relevant definitions are in scope) interpreting the output of show as an expression gives a value equivalent to deserializing it with read.

    If you want nice, formatted output that doesn't look like Haskell source, the standard term for that is still "pretty printing", and there's no standard generic way to do it. There are pretty-printing libraries out there that provide primitives to build your own pretty-printers, however, if you browse around Hackage a bit. Note that even if they talk about pretty-printing syntax trees in a compiler that's just an example; any tree-like structure ought to work just as well.

    As a quick alternative, you might wish that the output of show was at least better-looking quasi-source-code. This is reasonable and possible, since read is smart enough to ignore whitespace and such. The groom package provides this functionality, in a "doing the stupidest thing that could possibly work" manner: it parses the output of show as Haskell source, then pretty-prints that. In practice, this works pretty well.

    0 讨论(0)
提交回复
热议问题