Preferred method for viewing code generated by Template Haskell

吃可爱长大的小学妹 提交于 2019-11-28 06:12:22

You may be able to use pprint or ppr from Language.Haskell.TH.Ppr (imported automatically with Language.Haskell.TH):

GHCi> expr <- runQ [| \f g x -> f (x*2 + 3) . g |]
GHCi> putStrLn $ pprint expr
\f_0 g_1 x_2 -> f_0 ((x_2 GHC.Num.* 2) GHC.Num.+ 3) GHC.Base.. g_1

It's not pretty, but it is valid Haskell. You should be able to make the output nicer by stripping off module prefixes from Prelude names (although you might need to be careful to only strip the expected prefix; Foo.* is a perfectly valid infix operator, after all).

Are you looking for the -ddump-splices flag to the compiler?

Rudy Matela

As a complement to ehird answer:

Note that using runQ directly from GHCi in general might not work (e.g.: TH generators that use reify operations, cf. comments above the runQ declaration).

When that fails, you can pprint (or show), transform intro a string expression stringE then splice as an argument to putStrLn:

> putStrLn $(stringE . pprint =<< [| \f g x -> f (x*2 + 3) . g |])
\f_0 g_1 x_2 -> f_0 ((x_2 GHC.Num.* 2) GHC.Num.+ 3) GHC.Base.. g_1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!