Reputation: 3211
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?
Upvotes: 0
Views: 415
Reputation: 137977
Change (or remove) the type of altSumOfDigits
to return a [Integer]
.
Including the error in the question is good form, and here it is:
Couldn't match type `a' with `Integer'
The type of altSumOfDigits
takes a list of Integer
, but returns a list of any type a
, according to the type you have declared. So it is polymorphic in its return type.
However, you call digits
from within altSumOfDigits
, which must return a list of Integer
only. There is thus no way your altSumOfDigits
could return anything other than a list of [Integer]
.
Upvotes: 4