问题
I've been staring at this code for quite some time now and I can't get my head around that error message.
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" takes an Integer and returns a list with all its divisors.
"length'" is the same as the built-in "length", only it returns an Integer.
"divLengths" is an infinite list of tuples of a Integer and the number of its divisors.
"divLengths'" only returns the number of divisors of the numbers.
"hcn" is supposed to be an infinite list of highly composite numbers (if the number of divisors is the same as the maximum of all numbers of divisors of all numbers (up to the number being checked)).
However, i get this error when trying to load the .hs in ghci:
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)'
Can you please help me out here?
Best regards, Lukas
回答1:
The problem is that take
takes an Int
, so GHC infers from that that n
must be Int
. No problem, you can use fromIntegral
to convert between any integral types.
There is also another problem with max
which is supposed to take two arguments. You probably meant to use maximum
, which takes a list instead.
Try something like this:
hcn :: [Integer]
hcn = [n | n <- [1..], maximum (take (fromIntegral n) divLengths') == length' (divisors n)]
来源:https://stackoverflow.com/questions/16492356/haskell-couldnt-expected-type-integer-with-actual-type-int