Alex M
Alex M

Reputation: 3513

Loading dynamic haskell module

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 function.

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.

Upvotes: 4

Views: 867

Answers (2)

Don Stewart
Don Stewart

Reputation: 138007

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.

Upvotes: 3

Dan Burton
Dan Burton

Reputation: 53725

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

Upvotes: 0

Related Questions