如何在Haskell中覆盖Show一些基本类型的实例? [英] How to override Show instance of some basic types in Haskell?

查看:67
本文介绍了如何在Haskell中覆盖Show一些基本类型的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Haskell中编写一些程序,处理很多基本类型,如Word32/Word64等. 我经常使用ghci来测试功能,请在终端中查看结果.

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.

为了方便快捷,我总是以十六进制显示数据.

To be convenient and fast, I always show data in hexadecimal e.g.

data Human = M Int | F Int
instance Show Human where
    show M x = printf "man, age %d" x
    show F x = printf "woman, age %d" x

但我希望基本类型以十六进制显示(尤其是ghci). 我发现实例声明不能被覆盖. 而我不想想要像这样扭曲所有人:

but I want basic types to be showed in hexadecimal (espacially in ghci). I found instance declaration cannot be overridden. and I don't want to warp all of them up like:

newtype MyInt = MyInt Int
instance Show MyInt where
    ...

看起来有点愚蠢.

我可以为ghc修改软件包base中的某些代码吗? 我只希望一切都变成十六进制".我只想要ghci显示"hex".我怎么能做到呢?

Can I modify some code in the package base for ghc? I just want everything becoming "hex". I just want ghci showing "hex". how could I achieve it?

由于我们所有人都同意,覆盖放映是不正确且不切实际的, 欢迎回答以更好的方式在ghci中以十六进制显示数字"的答案.

Since all of us agree that override Show is not proper and impractical, Any answer of "better ways to show Numeric in hexadecimal in ghci" is welcomed.

推荐答案

这将滥用Show实例.它并不是真的要格式化.如果要以十六进制显示内容,只需使用一个函数即可进行转换.例如,您可以使用Numeric中的showHex来创建一个小的助手,如下所示:

That would be abusing the Show instance. It's not really meant for formatting. If you want to show something in hexadecimal, just use a function to do the conversion. For example, you can use showHex from Numeric to make a small helper like this:

> import Numeric
Numeric> let hex x = showHex x ""
Numeric> hex 123456
"1e240"

这篇关于如何在Haskell中覆盖Show一些基本类型的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆