2

I would like to define a data family that supports polymorphism for explicitly uninstantiated cases:

data family Foo a

-- handles some specific case
data instance Foo Int = CreateInt Int Int String

-- handles all other cases
data instance Foo bar = CreateBar bar

Is this possible?

Petras Purlys
  • 1,093
  • 6
  • 18
  • 1
    This seems to be strictly related, if not a duplicate, to https://stackoverflow.com/questions/49433716/why-cant-we-define-closed-data-families – chi Apr 17 '18 at 11:07

1 Answers1

6

Use a closed type family. Unfortunately, this requires an extra newtype wrapper:

newtype Foo a = CreateFoo {getFoo :: Foo' a}

type family Foo' a where
  Foo' Int = IntFoo
  Foo' bar = Barbar bar

data IntFoo = CreateInt Int Int String
data Barbar bar = CreateBar bar
chi
  • 111,837
  • 3
  • 133
  • 218
leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
  • Thanks, just a small remark: Foo Int = IntFoo should be Foo' Int = IntFoo. Same with bar. SO does not allow me to fix this as it's less than 6 symbols.. :) – Petras Purlys Apr 17 '18 at 12:42