3

Is it possible to specify that every member of a datakind satisfies a typeclass, such that the class constraint is implied? E.g.

data AB = A | B
class Foo (a :: AB) where get :: proxy a -> String
instance Foo A where get _ = "A"
instance Foo B where get _ = "B"

-- note lack of constraint here
get' :: proxy (a :: AB) -> String
get' = get

Basically a is an AB so we're sure there's an instance of Foo for it. I find it unlikely -- where is it going to get the Foo dictionary? -- but I've seen some magic in my day.

Alec
  • 31,829
  • 7
  • 67
  • 114
luqui
  • 59,485
  • 12
  • 145
  • 204
  • I closed this as a duplicate of http://stackoverflow.com/questions/32408110/datakinds-and-type-class-instances but reopened it. The separate `Foo` class constrained to only operate on `AB` might leave room for magic I can't imagine. – Cirdec Dec 13 '16 at 21:50

1 Answers1

6

No, you can't do that. The primary problem is that, as you mention, there's nothing there to get you a dictionary. But the other problem is that your claim that every type in AB is an instance of Foo is false.

type family Broken :: AB where
dfeuer
  • 48,079
  • 5
  • 63
  • 167
  • Or `GHC.Exts.Any :: AB`. – Alec Dec 13 '16 at 23:09
  • Interesting, I hadn't considered that all kinds might have a "bottom", which would certainly put a damper on things semantically. Then it makes sense to constrain to normal-form kinds, perhaps with a class `NF k`, which could then be used to provide the necessary dictionaries. Hmmm.... anyway, thanks for the insight – luqui Dec 14 '16 at 00:14
  • @luqui, a singleton will do. `data ABy x where Ay :: ABy 'A; By :: ABy 'B`. If you like, `class KnownAB x where knownAB :: ABy x`. Pattern matching on `knownAB` lets you use the instances. – dfeuer Dec 14 '16 at 00:37
  • 1
    @luqui, you can use a singleton like **dfeuer** suggested, but also get rid of explicit pattern matching like [this](http://lpaste.net/349915). – effectfully Dec 14 '16 at 08:56
  • 1
    More on stuck type families [on Richard Eisenberg's blog](https://typesandkinds.wordpress.com/2015/09/09/what-are-type-families/) – Benjamin Hodgson Dec 14 '16 at 10:27