Search code examples
haskellruntimeevaluationghcghc-api

Evaluation of Haskell Statements/Expressions using GHC API


For a tool I'm writing ( http://hackage.haskell.org/package/explore ) I need a way to read haskell function definitions at run-time, apply them to values from my tool and retrieve the results of their application.

Can anyone give me a very basic example using GHC (6.10.4 or 6.12.1) API?

example function definition to be read from a file at run-time:

f x = 10**(4/1102*x - 1)

expected program output

--mapM_ print $ map f [428, 410, 389]
3.577165388142748
3.077536885227335
2.5821307011665815

!!UPDATE!!
I posted a quick answer but it creates an object file in the directory of execution, any tips to avoid this and avoid all file IO is most welcome. I want to also see a version that does everything in memory: user provides the function definition in a GUI for example and the compilation / evaluation does not create any object files.


Solution

  • Use hint. It's a GHCi-like wrapper around the GHC API that is not very difficult to use.

    If you want an example of its use, I used it in my Yogurt project.