I am a newbie to haskell and have a working code below as follows.
sum' :: (Num a) => [a] -> a
sum' [] = 0
sum' (x:xs) = x + sum' xs
What i try to do is to be more specific about my types.Instead of using 'a' only i try to write my code like that.
sum' :: (Num a, Num b) => [a] -> b
sum' [] = 0
sum' (x:xs) = x + sum' xs
When i do is i get an error.Error is as follows: Couldn't match expected type ‘b’ with actual type ‘a’ ‘a’ is a rigid type variable bound by the type signature for sum' :: (Num a, Num b) => [a] -> b at baby.hs:2:9 ‘b’ is a rigid type variable bound by the type signature for sum' :: (Num a, Num b) => [a] -> b at baby.hs:2:9
I think i don't really understand the meaning of '=>'. The part confuses me is what comes before '=>'. Sometimes a thing like that '(Show a) =>' and usually just types just like in my code. Please help thanks in advance.
+
's type signature isNum a => a -> a -> a
, i.e. it returns value of the same type as its arguments. But you want it to produce a value of a different type than it's arguments (b
againsta
s), which it simply cannot do. – Michail[a] -> b
means you have no idea what type is being returned; the caller can specify anything they want. With[a] -> a
, you are at least saying that the return type must be the same as the type stored in the input list. – chepner