The code below starting with digits returns a List of integers. The code starting with altSumOfDigits should return just the same list, but instead Prelude is complaining about a type error, which i don’t understand at this point.
Couldn't match expected type `a' against inferred type `Integer'
digits' :: Integer -> [Integer]
digits' 0 = []
digits' x = (x `mod` 10) : digits' (x `div` 10)
digits :: Integer -> [Integer]
digits 0 = [0]
digits x = reverse $ digits' x
altSumOfDigits :: Integer -> [a]
altSumOfDigits num = [ x | x <- (digits num)]
(I know that altSumOfDigits num = [ x | x <- (digits num)] is rather useless in this form. I’m going to extend its functionality with an if-expression and operations on the single Integers later.)
Any explanations why this doesn’t work?
Change (or remove) the type of
altSumOfDigitsto return a[Integer].Including the error in the question is good form, and here it is:
The type of
altSumOfDigitstakes a list ofInteger, but returns a list of any typea, according to the type you have declared. So it is polymorphic in its return type.However, you call
digitsfrom withinaltSumOfDigits, which must return a list ofIntegeronly. There is thus no way youraltSumOfDigitscould return anything other than a list of[Integer].