Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get a type of any expression using Template Haskell?

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.

like image 287
Petr Avatar asked Jan 31 '14 21:01

Petr


People also ask

Why Template Haskell?

Template Haskell, also known as TH, is a set of functions and datatypes exposed through the template-haskell package, which allows the programmer to manipulate Haskell code programmatically. Some of the things Template Haskell allows are: Generate new functions or datatypes procedurally.

What does () mean in Haskell?

() is very often used as the result of something that has no interesting result. For example, an IO action that is supposed to perform some I/O and terminate without producing a result will typically have type IO () .


1 Answers

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.

like image 152
Christian Conkle Avatar answered Oct 17 '22 13:10

Christian Conkle