1
votes

I have a simple function defined below:

allZero :: Num a => [a]-> Bool
allZero [] = False
allZero xs = and (map (== 0) xs)

This returns an error message upon loading:

Could not deduce (Num a) arising from the literal `0'

What is the problem with this function? How do I oveload the number 0 to be of any numeric type a?

1
Because the place of Num in the type-class hierarchy changed (a while ago), it may be worth specifying which version of GHC you're using.jub0bs
By the way, I would expect allZero [] to return true. You can also use all (==0) xs instead of and (map (==0) xs).chi

1 Answers

7
votes

This code compiles once you add an Eq a constraint to allZero. There should be no other issues compiling this code.

allZero :: (Num a, Eq a) => [a]-> Bool
allZero [] = False
allZero xs = and (map (== 0) xs)

As some commenters pointed out, the first case is non-standard, as allZero of [] is typically True. With that definition, the first case becomes redundant.