Reputation: 28760
I have the following use of foldl which is erroring:
elementAt :: [a] -> Int -> a
elementAt [] x = error "No empty lists for element-at"
elementAt xs x = foldl(\acc (a, b) -> if(b == x) then a else acc) 0 $ zip xs [0..]
When I try and compile I get this error:
exercises.hs:8:67: error: * No instance for (Num a) arising from the literal
0' Possible fix: add (Num a) to the context of the type signature for: elementAt :: [a] -> Int -> a * In the second argument of
foldl', namely `0' In the expression: foldl (\ acc (a, b) -> if (b == x) then a else acc) 0 In the expression: foldl (\ acc (a, b) -> if (b == x) then a else acc) 0 $ zip xs [0 .. ] Failed, modules loaded: none.
Upvotes: 0
Views: 77
Reputation: 370082
When you don't find the element, the result of your function is 0
. That only makes sense if you're working with a list of numbers. If you pass in a list of strings and then return either a string from the list or the number 0
, that'd be a clear type error.
So your function only works with lists of numbers and your type signature must reflect that by adding a Num a
constraint.
However a better solution would be to not use 0
as the default value and use a Maybe
instead. That way you don't have to restrict yourself to lists of numbers.
Upvotes: 5