I am following a tutorial and found this code:
data A = B | C deriving(Eq)
class K a where
f :: a -> Bool
instance K A where
f x = x == C
f _ = False
call = f B
Why do I need f _ = False
? I get the same result without it.
CodePudding user response:
The answer is simply: you don't need f _ = False
here. In fact, if you compile with -Wall
then the compiler will warn you that this clause is redundant, because the f x = ...
clause already catches everything.
If the tutorial told you to have that extra clause, well, it's wrong.
CodePudding user response:
As pointed out, it's not necessary.
You might need (or want) that line, though, if you had a slightly different definition, one that does not require an Eq
instance:
data A = B | C
class K a where
f :: a -> Bool
instance K A where
f C = True
f _ = False
Instead of comparing x
to C
, you can match the argument directly against C
, then define f
to return False
for all other values. This makes more sense if there were more constructors that could produce False
.
data A' = B | C | D
instance K A' where
f C = True
f _ = False -- in place of f B = False and f D = False