【问题标题】:Haskell: Couldn't expected type 'Integer' with actual type 'Int'Haskell:不能预期类型“Integer”与实际类型“Int”
【发布时间】:2013-05-10 23:55:37
【问题描述】:

我已经盯着这段代码看了很长一段时间了,我无法理解那个错误消息。

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)]

"divisors" 接受一个整数并返回一个包含所有除数的列表。

“length”与内置的“length”相同,只是返回一个整数。

“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)'

你能帮帮我吗?

最好的问候, 卢卡斯

【问题讨论】:

    标签: haskell numbers composite


    【解决方案1】:

    问题在于take 接受Int,因此GHC 推断n 必须是Int。没问题,你可以使用fromIntegral在任意整数类型之间进行转换。

    max 还有另一个问题,它应该接受两个参数。您可能打算使用maximum,它接受一个列表。

    试试这样的:

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

    【讨论】:

      猜你喜欢
      • 2021-05-28
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多