据我所知,这个代码片段应该可以毫无问题地编译:
import Data.Digits (digits)
-- |convert integer to arbitrary base with specified charset
-- base/radix is charset string length.
-- eg. convert the integer 255 to hex:
-- intToBaseN 255 "0123456789abcdef" = "ff"
numToBaseN :: Integral n => n -> [Char] -> String
numToBaseN num charlst = map (\i -> charlst !! (fromIntegral i)) lst where
lst = digits (length charlst) num
但是 GHC 提示
num 表达式中的
lst 不是
Int 。但是
digits 的类型是
digits :: Integral n => n -> n -> [n]
它不需要
Int 作为参数,只需要一个积分,
numToBaseN 的类型签名也可以。
!! 需要一个 Int,这就是使用
fromIntegral 转换它的原因。
这里发生了什么?
如果我用
num 替换
(fromIntegral num) ,它会编译,但是我失去了转换整数(即任意大整数)的能力。
请您参考如下方法:
digits 的两个参数需要具有相同的类型和length charlst有类型 Int , 所以 num还必须有类型 Int .
It compiles if I replace num with (fromIntegral num), but then I lose the ability to convert an Integer
如果您申请
fromIntegral至
length charlst相反,它会将其转换为任何类型
num是,所以它会按照你想要的方式工作。

