Home > Blockchain >  How can I implement Describable for Bool?
How can I implement Describable for Bool?

Time:11-05

I am reading Get Programming with Haskell by Will Kurt.

It says:

To help solidify the idea, you’ll write a simple type class of your own. Because you’re learning Haskell, a great type class to have is Describable . Any type that’s an instance of your Describable type class can describe itself to you in plain English. So you require only one function, which is describe . For whatever type you have, if it’s Describable , calling describe on an instance of the type will tell you all about it. For example, if Bool were Describable , you’d expect this:

GHCi> describe True
"A member of the Bool class, True is opposite of False"
GHCi> describe False
"A member of the Bool class, False is the opposite of True"

The code provided is:

class Describable a where
    describe :: a -> String

i think i have to use deriving (Describable) on Bool type. Then have to implement the describe function. However, I am not sure how the code will actually look like.

Please help.

CodePudding user response:

You can only use deriving for the classes that support auto-deriving, which won't work for this Describable class. You'll need to create an instance:

class Describable a where
    describe :: a -> String

instance Describable Bool where
    describe True = "..."
    describe False = "..."
  • Related