使用模板生成函数定义 haskell

Generate function definition with template haskell

如何编写模板 Haskell 函数使得:

mkFunc "func"

生成

func = "func"

我试过了

mkFunc x = ValD (VarP x) (NormalB (LitE (StringL x))) []

但它不进行类型检查:

Couldn't match type ‘Name’ with ‘[Char]’
Expected type: String
  Actual type: Name
In the first argument of ‘StringL’, namely ‘x’
In the first argument of ‘LitE’, namely ‘(StringL x)’

另外,在定义了mkFunc之后,我如何定义mkFuncs来生成一个函数定义列表?

您可以使用 runQ 获得帮助并查看它生成的抽象语法树:

λ> runQ [d|func = "func"|]
[ValD (VarP func_4) (NormalB (LitE (StringL "func"))) []]

然后您可以将其转化为代码:

-- External.hs
{-#LANGUAGE TemplateHaskell#-}

module External where

import Language.Haskell.TH

mkFunc :: String -> Q [Dec]
mkFunc str = return [ValD (VarP str') (NormalB (LitE (StringL str))) []]
    where str' = mkName str

和另一个模块:

-- Other.hs
{-#LANGUAGE TemplateHaskell#-}
import External

$(mkFunc "haskell")

main = print haskell

ghci 中的演示:

λ> main
"haskell"

创建 mkFuncs 很简单:

mkFuncs :: [String] -> Q [Dec]
mkFuncs srt = return decs
    where dec n s = ValD (VarP n) (NormalB (LitE (StringL s))) []
          srt' = map (\x -> (mkName x, x)) srt
          decs = map (\(n,s) -> dec n s) srt'