2016-06-20 87 views
2

我试图以二进制格式打印数量,而且我发现功能混淆showIntAtBase签名

showIntAtBase :: (Integral a, Show a) => a -> (Int -> Char) -> a -> ShowS 

,但我不明白它是如何工作的,尤其是我不知道有什么目的做功能参数从Int转换为Char。直观地看,这个功能应该仅取2个参数,以显示数字和碱,以显示它的,并且这似乎是从Numeric在多个特定功能的情况下,像

showHex :: (Integral a, Show a) => a -> ShowS 

showOct :: (Integral a, Show a) => a -> ShowS 

那么(Int -> Char)参数的目的是什么showIntAtBase

+1

查看文档[这里](http://hackage.haskell.org/package/base-4.9.0.0/docs/Numeric.html#v:showIntAtBase),我发现[这里](https://www.haskell.org/hoogle/?hoogle=showintatbase) – pdexter

回答

3
Prelude Numeric> putStrLn $ showIntAtBase 10 (\n -> ['0'..'9']!!n) 26734 "" 
26734 
Prelude Numeric> putStrLn $ showIntAtBase 10 ("⁰¹²³⁴⁵⁶⁷⁸⁹"!!) 26734 "" 
²⁶⁷³⁴ 
Prelude Numeric> putStrLn $ showIntAtBase 16 ("ABCdef"!!) 0xbeef "" 
Beef 

请注意,!!不应该用于严重的应用程序,它效率低下。更好地使用像

Prelude Numeric> let c0 = fromEnum '0' in showIntAtBase 10 (toEnum . (+c0)) 26734 "" 
"26734" 
+0

'ord'和'chr'似乎更适合,喜欢'fromEnum' /'toEnum'的任何一点? – pdexter

+0

@pdexter并不是真正重要的IMO ......它们无论如何都是等价的,我认为GHC会将它们重写为相同的代码。我觉得'ord' /'chr'有点无用。 – leftaroundabout