简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM