9
4

1 回答 1

5

First note that Enum and c are not constraints by themselves: They have kind * -> Constraint, not kind Constraint. So what you want to express with Enum ⊆ c is: c a implies Enum a for all a.

Step 1 (explicit witnesses)

With :- from Data.Constraint, we can encode a witness of the constraint d ⊆ c at the value level:

type Impl c d = forall a . c a :- d a

We would like to use Impl in the definition of succSome as follows:

succSome :: Impl c Enum -> Some c -> Some c
succSome impl (Specimen a) = (Specimen $ succ a) \\ impl

But this fails with a type error, saying that GHC cannot deduce c a0 from c a. Looks like GHC chooses the very general type impl :: forall a0 . c a0 :- d a0 and then fails to deduce c a0. We would prefer the simpler type impl :: c a :- d a for the type variable a that was extracted from the Specimen. Looks like we have to help type inference along a bit.

Step 2 (explicit type annotation)

In order to provide an explicit type annotation to impl, we have to introduce the a and c type variables (using the ScopedTypeVariables extension).

succSome :: forall c . Impl c Enum -> Some c -> Some c
succSome impl (Specimen (a :: a)) = (Specimen $ succ a) \\ (impl :: c a :- Enum a)

This works, but it is not exactly what the questions asks for.

Step 3 (using a type class)

The questions asks for encoding the d ⊆ c constraint with a type class. We can achieve this by having a class with a single method:

class Impl c d where
  impl :: c a :- d a

succSome :: forall c . Impl c Enum => Some c -> Some c
succSome (Specimen (a :: a)) = (Specimen $ succ a) \\ (impl :: c a :- Enum a)

Step 4 (usage example)

To actually use this, we have to provide instances for Impl. For example:

instance Impl Integral Enum where
  impl = Sub Dict

value :: Integral a => a
value = 5

specimen :: Some Integral
specimen = Specimen value

test :: Some Integral
test = succSome specimen
于 2013-07-06T18:29:13.403 回答