In Haskell, how to get such a custom class automatically?

Codes look 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 that has the MyAnd function, I thought that it is a common one and the only restriction is a must have an instance of the Show class ..

In the type TrafficLight it is already derived from a class of type Show . 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 any ideas about this?

+8
source share
3 answers

You cannot use output with custom classes. Typically, deriving automatically generates code for the given methods of the class, which is possible only because the compiler knows what these methods should do, and thus can generate suitable implementations based on your type structure. This is clearly not possible for custom classes, since the compiler does not know how methods should behave.

In your case, it looks like you want to use standard implementations of one method that your class has, so the compiler should not generate an implementation. Of course, this means that deriving is not required at all, and you can simply use an instance declaration without a body.

PS: If you always want to use the standard implementation of the method, it may make sense not to use any class at all, but simply define myAnd as a function.

+9
source

For this particular problem, you can simply avoid defining a custom class:

 data TrafficLight = Red | Yellow | Green deriving Show myAnd :: (Show a) => a -> a -> String x `myAnd` y = (show x) ++ " and " ++ (show y) 

Now myAnd applicable to TrafficLight (as well as to all other Show capable types).

+8
source

I found this question while trying to figure out how to use the GHC DeriveAnyClass , which was missing only three weeks ago when asked about it.

Using it, the following works as you expect:

 {-# LANGUAGE DeriveAnyClass #-} class Show a => MyAnd a where myAnd :: a -> a -> String x 'myAnd' y = (show x) ++ " and " ++ (show y) data TrafficLight = Red | Yellow | Green deriving (Show, MyAnd) 

However, it should be used with caution, as it will literally output any class, creating empty instances when necessary

0
source

Source: https://habr.com/ru/post/987373/


All Articles