mb14
mb14

Reputation: 22596

How to solve conflicting instance in type families?

I'm trying to do a 'UnMaybe' type family but it doesn't compile (instance family conflicting).

Here is my code

{-# LANGUAGE TypeFamilies #-}

type family UnMaybe a :: *

type instance UnMaybe (Maybe a) = a
type instance UnMaybe a = a

Error message

test.hs:4:16:
    Conflicting family instance declarations:
       type instance UnMaybe (Maybe a)
       -- Defined at test.hs:4:16
       type instance UnMaybe a
       -- Defined at test.hs:5:15

I understand why it's not working, anyway is there another way to achieve the same result (or an extension to activate which will allow it?)

Upvotes: 6

Views: 526

Answers (1)

kosmikus
kosmikus

Reputation: 19637

If you really need this, you can use a closed type family (requires at least GHC 7.8):

{-# LANGUAGE TypeFamilies #-}

type family UnMaybe a :: * where
  UnMaybe (Maybe a) = a
  UnMaybe a         = a

Now:

GHCi> :kind! UnMaybe (Maybe Int)
UnMaybe (Maybe Int) :: *
= Int
GHCi> :kind! UnMaybe Bool
UnMaybe Bool :: *
= Bool

Upvotes: 11

Related Questions