Home > Back-end >  Matching on a particular type of a parametric type
Matching on a particular type of a parametric type

Time:11-22

I'm trying to work with an external library that has provided a parametric type like this:

data ParametricType a = TypeConstructor a

I have a typeclass, something like this:

class GetsString a where
    getString :: a -> String

and I'd like to execute some code if ParametricType's a is a specific type. I've tried narrowing the type when instantiating the typeclass:

data HoldsString = HoldsString String

instance GetsString (ParametricType HoldsString) where
    getString (TypeConstructor (HoldsString str)) = str

which errors with Illegal instance declaration for‘GetsString (ParametricType HoldsString)’(All instance types must be of the form (T a1 ... an)

and I've tried pattern matching on the type:

instance GetsString (ParametricType a) where
    getString (TypeConstructor (HoldsString str)) = str

for which I receive Couldn't match expected type ‘a’ with actual type ‘HoldsString’‘a’ is a rigid type variable bound by the instance declaration.

Is there a way to do this, or am I conceptually on the wrong track here?

CodePudding user response:

You're just missing the FlexibleInstances extension. Put {-# LANGUAGE FlexibleInstances #-} at the top of your file, or do :set -XFlexibleInstances if you're typing into GHCi directly, and then your first attempt will work.

  • Related