I'm looking for a way to load a Haskell function from a string to run. I know the type before hand, but don't know the contents of the 开发者_如何学JAVAfunction.
Ideally, a solution would be quick and not need to run in IO.
I've been looking at hint (Language.Haskell.Interpreter), but it doesn't fit bill (eval calls show, modules must be in files).
Any help would be appreciated.
hint
and plugins
are the main options. hint
lets you interpret functions as bytecode, plugins
uses compiled object code.
Note that since these 'eval' functions must be type-checked prior to running them, they're rarely pure values, as evaluation may fail with a type error.
The abstract answer is that you just have to make (->)
an instance of Read
(and possibly Show while you're at it)
How on earth you are supposed to do that, I don't know. It's no small task to interpret code.
If you are dealing with simple functions, the I would suggest creating an algebraic data type to represent them.
data Fun = Add | Subtract | Multiply deriving (Eq, Show, Read)
runFun Add = (+)
runFun Subtract = (-)
runFun Multiply = (*)
*Main> runFun (read "Add") 2 3
5
*Main> runFun (read "Multiply") 2 3
6
*Main> runFun (read "Subtract") 2 3
-1
精彩评论