trollinator
trollinator

Reputation: 73

Haskell instance multiple context

class Countable a where
  count :: [a]

Class Countable is a class that should implement the method count, which returns a list all possible values of a without duplicate. For example if a is Bool, then count should be [True, False].

Lets say we want to have an instance Countable (Maybe a) assuming a is already Countable, then we can just implement count accordingly.

instance Countable a => Countable (Maybe a) 
   count = map Just countable ++ [Nothing]

But what if we want an instance which has multiple contexts? How can we access the function count of a and b? count doesn't take any parameter so how should haskell find out if a or b is meant? Like

instance (Countable a, Countable b) => Countable (a, b) 

Upvotes: 0

Views: 130

Answers (1)

SergeyKuz1001
SergeyKuz1001

Reputation: 875

Yes, you are right. You can write this instance like so:

instance (Countable a, Countable b) => Countable (a, b)
    count = [ (x, y) | x <- count, y <- count ]

So, outer count has type [(a, b)], and inner counts have types [a] and [b] accordingly.

Upvotes: 2

Related Questions