Why does this not work?
summ :: (Num a) => [a] -> Int
summ [] = 0;
summ (x:list) = x summ list
Is it because it is not sure that x summ list is always an Int? If a is Num isn't there made some kind of conversion ?
CodePudding user response:
You make use of ( ) :: Num a => a -> a -> a in x summ list. As the type signature suggests, both operand and the result all have the same type. If you thus have a x of type Num a => a, then summ list also should be of the same type a, and not an Int.
You thus should work with:
summ :: Num a => [a] -> a
summ [] = 0
summ (x:list) = x summ list
with a as result type. If you use a list of Ints as parameter, then you will retrieve an Int as result, and if you use a list of Integers as parameter, then this will produce an Integer.
If you know the items of your list have a type that is a member of the Integral typeclass, you can make useo f fromIntegral :: (Integral a, Num b) => a -> b to convert these to an Int:
summ :: Integral a => [a] -> Int
summ [] = 0
summ (x:list) = fromIntegral x summ list
but this is likely not a good idea, since of you work with an Integer, such numbers can get arbitrary large, and thus might result in overflow.
