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

℡╲_俬逩灬. 提交于 2019-12-04 01:58:17

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!