10

I need a (quick and dirty) way to get some representation of the type of a Haskell expression that is given as a string.

I currently see 3 options:

  • Use GHC API -- however, the documentation loses me pretty quickly.
  • Use some other type inference tool -- I've been suggested to try haskell-type-exts, but it fails to type all but the most trivial expressions. I don't know of any other such tool.
  • Roll my own HM inferer -- I'd avoid this unless absolutely necessary

I don't even need a complete solution, in the sense that a library/tool that can type a reasonable basic subset of Haskell would well suffice for me.

So what is the simplest way to achieve this?

xcvii
  • 450
  • 3
  • 17
  • Have a look at [other Haskell implementations](http://www.haskell.org/haskellwiki/Implementations) - some of them could be simpler to use than GHC. – Petr May 04 '13 at 11:55
  • 2
    If you go writing your own, Mark P. Jones' [THIH](http://web.cecs.pdx.edu/~mpj/thih/) may be a good start. – Daniel Fischer May 04 '13 at 12:11

1 Answers1

17

The hint package offers a somewhat restricted, but perhaps more understandable interface to the GHC API. Perhaps it is sufficient for your purposes? If not, you can perhaps look at the sources to get a better idea of how to use the GHC API directly.

Here's an example program:

import Language.Haskell.Interpreter

main :: IO ()
main = do
  r <- runInterpreter $ do
    setImports ["Prelude"]
    typeOf "map (+1)"
  either print putStrLn r

If run, this prints

Num b => [b] -> [b]
kosmikus
  • 19,549
  • 3
  • 51
  • 66