The codes looks like this:
class MyAnd a where
myAnd :: (Show a) => a -> a -> String
x `myAnd` y = (show x) ++ " and " ++ (show y)
data TrafficLight = Red | Yellow | Green deriving(Show, MyAnd)
Here MyAnd
is a type class which has a function myAnd
, I thought it is generic and the only constraint is the a
has to has an instance of Show
class..
In the TrafficLight
type, it already derived from Show
type class. However, when I compiled the codes, the compiler complains
Can't make a derived instance of ‘MyAnd TrafficLight’:
‘MyAnd’ is not a derivable class
In the data declaration for ‘TrafficLight’
Failed, modules loaded: none.
Does anyone have ideas about this?
The second line, deriving (Eq, Show) , is called the deriving clause; it specifies that we want the compiler to automatically generate instances of the Eq and Show classes for our Pair type. The Haskell Report defines a handful of classes for which instances can be automatically generated.
What's a typeclass in Haskell? A typeclass defines a set of methods that is shared across multiple types. For a type to belong to a typeclass, it needs to implement the methods of that typeclass. These implementations are ad-hoc: methods can have different implementations for different types.
An instance of a class is an individual object which belongs to that class. In Haskell, the class system is (roughly speaking) a way to group similar types. (This is the reason we call them "type classes"). An instance of a class is an individual type which belongs to that class.
The shows functions return a function that prepends the output String to an existing String . This allows constant-time concatenation of results using function composition.
You can't use deriving with user-defined classes. Usually deriving
automatically generates code for the given class's methods, which is only possible because the compiler knows what the methods are supposed to do and can thus generate suitable implementations based on your type's structure. This is obviously not possible for user-defined classes as the compiler has no way of knowing how the methods are supposed to behave.
In your case it looks like all you want is to use the default implementations of the one method your class has, so no implementation would need to be generated by the compiler. Of course that means that deriving
isn't necessary at all and you can just use an instance declaration without a body.
PS: If you'll always want to use the default implementation of the method, it might make the most sense not to use a class at all, but just define myAnd
as a function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With