xcvii
xcvii

Reputation: 470

Infer type of a string containing a Haskell expression

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:

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?

Upvotes: 10

Views: 324

Answers (1)

kosmikus
kosmikus

Reputation: 19637

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]

Upvotes: 17

Related Questions