Why can I not make String an instance of a typeclass?

前端 未结 4 719
甜味超标
甜味超标 2020-12-12 16:05

Given:

data Foo =
  FooString String
  …

class Fooable a where --(is this a good way to name this?)
  toFoo :: a -> Foo
<
4条回答
  •  没有蜡笔的小新
    2020-12-12 16:27

    You're running into two limitations of classic Haskell98 typeclasses:

    • they disallow type synonyms in instances
    • they disallow nested types that don't in turn contain type variables.

    These onerous restrictions are lifted by two language extensions:

    • -XTypeSynonymInstances

    which allows you to use type synoyms (like String for [Char]), and:

    • -XFlexibleInstances

    which lift the restrictions on instance types being of the form T a b .. where the parameters are type variables. The -XFlexibleInstances flag allows the head of the instance declaration to mention arbitrary nested types.

    Note that lifting these restrictions can sometimes lead to overlapping instances, at which point, an additional language extension might be needed to resolve the ambiguity, allowing GHC to pick an instance for you.


    References::

    • Relaxed rules for the instance head, in the GHC User's Guide.

提交回复
热议问题