Data constructor in template haskell

橙三吉。 提交于 2019-12-04 02:32:05

The Template Haskell documentation lists the things you are allowed to splice.

A splice can occur in place of

  • an expression; the spliced expression must have type Q Exp
  • an type; the spliced expression must have type Q Typ
  • a list of top-level declarations; the spliced expression must have type Q [Dec]

In both occurrences of $n, however, you're trying to splice a name.

This means you can't do this using quotations and splices. You'll have to build declaration using the various combinators available in the Language.Haskell.TH module.

I think this should be equivalent to what you're trying to do.

genData :: Name -> Q [Dec]
genData n = fmap (:[]) $ dataD (cxt []) n []
                           [normalC n [strictType notStrict [t| Integer |]]] []

Yep, it's a bit ugly, but there you go. To use this, call it with a fresh name, e.g.

$(genData (mkName "Z5"))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!