Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of class instance declarations

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.

like image 820
zeppal Avatar asked Feb 21 '26 12:02

zeppal


2 Answers

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.

like image 92
leftaroundabout Avatar answered Feb 24 '26 19:02

leftaroundabout


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
like image 28
chepner Avatar answered Feb 24 '26 18:02

chepner