Template Haskell type quoting problems

2019-06-20 10:44发布

问题:

The TemplateHaskell quoting documents two quotes ('') as the way to get the Name of a type:

> ''String
GHC.Base.String

This works fine for this type (name). However, I can't find a way to make it work nice for e.g. Maybe String:

> ''Maybe String -- interprets String as a data constructor
> ''Maybe ''String -- wants to apply ''String to the Name type

I know I can workaround via using [t| Maybe String |], but this is then in the Q monad, and requires type changes, and I think is not type-checked at the respective moment, only when spliced in.

I can also work around by first defining a type alias, type MaybeString = Maybe String, and then using ''MaybeString, but this is also cumbersome.

Any way to directly get what I want simply via the '' quotation?

回答1:

'' is used to quote names, not types. Maybe is a name, Maybe String is not. It is therefore not too surprising that you have to give your type a name by defining a type alias, before you can quote that name.

[t| |] on the other hand, quotes types. Note the difference here.

Prelude> :t ''String
''String :: Language.Haskell.TH.Syntax.Name
Prelude> :t [t| String |]
[t| String |]
  :: Language.Haskell.TH.Syntax.Q Language.Haskell.TH.Syntax.Type

So I'm afraid you cannot use '' for what you're trying to do.



回答2:

I think what you're looking for is:

ConT ''Maybe `AppT` ConT ''String