是否有可能使用模板Haskell获取任何表达式的类型? [英] Is it possible to get a type of any expression using Template Haskell?

查看:142
本文介绍了是否有可能使用模板Haskell获取任何表达式的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定表达式 foo ,我可以声明一个顶级函数

  bar = foo 

并获取 foo as 输入 reifying bar

  case reify'bar 
VarI _ t _ _ - > t

是否有一种直接获取 foo ,而不会创建 bar 的冗余定义?理想情况下,可以根据 Exp - > Q类型

解决方案

您需要一个像 Exp - > Q Info Exp - > Q型,是吗? TH不提供这样的功能。生成 Info 的唯一TH函数是 reify ,并且没有其他TH类型似乎公开类型信息,重新过后。看起来,目前的TH API没有提供任意表达式的方法。



我不是GHC内部专家,但是在 compiler / typecheck / TcSplice.hs 似乎证实了 reify 通过查找一个已经编译的(和类型检查的)实体并将编译器对其类型等的已有知识转换成TH的 Info 类型。该信息对于任意 Exp 不存在。我想我们必须通过另一个编译器传递回表达式。


Given an expression foo, I could declare a top-level function

bar = foo

and get the type of foo as Type by reifying bar:

case reify 'bar of
  VarI _ t _ _ -> t

Is there a direct way of getting the type of foo, without creating the redundant definition of bar? Ideally as function of type Exp -> Q Type.

解决方案

You're asking for a function of a type like Exp -> Q Info or Exp -> Q Type, yes? TH doesn't provide such a function. The only TH function that produces an Info is reify, and no other TH type seems to expose the type information you're after. It appears that the current TH API does not provide a way to reify arbitrary expressions.

I'm not an expert in GHC's internals, but poking around in compiler/typecheck/TcSplice.hs seems to confirm that reify works by looking up an already-compiled (and typechecked) entity and converting the compiler's existing knowledge of its type etc. into TH's Info type. That information wouldn't exist for an arbitrary Exp. I imagine we'd have to plumb the expression back through another compiler pass.

这篇关于是否有可能使用模板Haskell获取任何表达式的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆