How to override Show instance of some basic types in Haskell?

后端 未结 4 1397
太阳男子
太阳男子 2021-01-18 05:19

I\'m writting some programs in Haskell, dealing with a lot of basic types like Word32/Word64 etc.. I use ghci to test the functions frequently, see the results in terminal.<

4条回答
  •  粉色の甜心
    2021-01-18 06:14

    No, there is no way to achieve this without newtypes; instances cannot be overriden.

    If you really want this, I would suggest defining your own typeclass, ShowHex, like Show but with all the instances printing in hex. However, I would consider your Show instance incorrect; Show instances are designed for debugging and serialisation, and should output syntactically valid code.1 Yours doesn't, so I would suggest either defining your own typeclass for displaying these values, or simply using a function.

    Modifying the code to base for this is impractical; not only would this change in semantics for the instances break a lot of packages, but it'd be a huge pain to get GHC to actually use your modified version.

    1 Ideally, the code they produce should be semantically valid Haskell that produces a value comparing equal to show's input, but this is not strictly necessary.

提交回复
热议问题