Search code examples
haskelltypesconstraintssynonym

Synonym to constrained type


I know I can create synonym for a type, for example:

type ListToArray a e = [e] -> a Int e

I also read that a constrained type is still a type, so I thought I can create a synonym for that too:

type (Data.Array.IArray.IArray a e) => ListToArray a e = [e] -> a Int e

However GHC complains:

parse error on input '=>'

Does GHC support synonyms to constrained types?


Solution

  • You can check the Haskell 2010 Report, the section about type synonyms states that the grammar for type synonyms is:

    type simpletype = type
    simpletype  →   tycon tyvar1 … tyvark       (k ≥ 0) 
    

    In other words: no you cannot put class constraints on the left of the = in a type declaration.

    Also note that you cannot have class constraints even on the right of the = in such declarations. The definition of type is:

    type    →   btype [-> type]         (function type)
    
    btype   →   [btype] atype       (type application)
    
    atype   →   gtycon
        |   tyvar
        |   ( type1 , … , typek )       (tuple type, k ≥ 2)
        |   [ type ]        (list type)
        |   ( type )        (parenthesised constructor)
    
    gtycon  →   qtycon
        |   ()      (unit type)
        |   []      (list constructor)
        |   (->)        (function constructor)
        |   (,{,})      (tupling constructors) 
    

    So the type non-terminal refers to a type without a context. In other words: no you cannot have a context in a type synonym, at least not in the general case.

    GHC has a lot of extension to Haskell's type system that can lift some of the above restrictions in certain situations (see this page.) however, AFAIK, none that achieves exactly what you want.