Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haskell - generate an instance for all classes except one specific type

Is it possible to do something like

class T a
class U a
instance U ()
instance ( NOT U a ) => T a

Context: I am trying to write a function that takes HLists and removes elements of a certain type (here the unit type).

I feel like there might be some issue with the open world assumption, but even being able to do it in a hardcoded manner (instead of NOT U a , something like NOT a~()) should seem possible.

edit: As pointed out in a comment by C.A. McMann, this question is pretty much an exact duplicate of mine. If a moderator feels like closing this, feel free to.

like image 967
rtpg Avatar asked Dec 19 '12 09:12

rtpg


1 Answers

You can do it using a trick of Oleg's, which even has its own library on hackage

By heavily abusing the type class system, it is possible to generate a fundep

class TypeEq a b result | a b -> result

such that TypeEq a b True only when a~b, and TypeEq a b False otherwise

so you can write

instance (TypeEq () a False) => T a

and I think that should work. I should be clear, this type equality test is pure evil in how it is implemented, but it does mostly work. Check out the code for that library if you want to understand how this works/generalize it (also read the HList paper).

If it is at all possible to do what you want to do without negative constraint, do that instead.

like image 105
Philip JF Avatar answered Oct 16 '22 16:10

Philip JF