Haskell:无法预期实际类型'Int'的'Integer'类型

arm*_*ves 3 haskell numbers composite

我已经盯着这段代码已经有一段时间了,我无法理解这条错误信息.

divisors :: Integer -> [Integer]
divisors n = [t | t <- [1..n], mod n t == 0]

length' :: [a] -> Integer
length' []      = 0
length' (x:xs)  = 1 + length' xs

divLengths :: [(Integer, Integer)]
divLengths = [(n, length' (divisors n)) | n <- [1..]]

divLengths' :: [Integer]
divLengths' = [length' (divisors n) | n <- [1..]]

hcn :: [Integer]
hcn = [n | n <- [1..], max (take n divLengths') == length' (divisors n)]
Run Code Online (Sandbox Code Playgroud)

"divisors"接受一个I​​nteger并返回一个包含所有除数的列表.

"length"与内置的"length"相同,只返回一个Integer.

"divLengths"是一个整数元组的无限列表及其除数的数量.

"divLengths'"仅返回数字的除数.

"hcn"应该是高度复合数字的无限列表(如果除数的数量与所有数字的所有除数的最大数量相同(直到被检查的数量)).

但是,在尝试加载ghci中的.hs时出现此错误:

Couldn't match expected type `Integer' with actual type `Int'
In the first argument of `divisors', namely `n'
In the first argument of length', namely `(divisors n)'
In the second argument of `(==)', namely `length' (divisors n)'
Run Code Online (Sandbox Code Playgroud)

你能帮帮我吗?

最好的问候,卢卡斯

ham*_*mar 9

问题是take需要一个Int,所以GHC的推断n必须是Int.没问题,你可以fromIntegral用来转换任何整数类型.

还有另一个问题,max它应该采取两个论点.您可能打算使用maximum,而是使用列表.

尝试这样的事情:

hcn :: [Integer]
hcn = [n | n <- [1..], maximum (take (fromIntegral n) divLengths') == length' (divisors n)]
Run Code Online (Sandbox Code Playgroud)