Loading the haskell dynamic module

I am looking for a way to load a Haskell function from a string to run. I know the type before hand, but I do not know the contents of the function.

Ideally, the solution will be fast and no need to run in IO.

I looked at the hint (Language.Haskell.Interpreter), but it is not suitable for counting (eval calls show, modules must be in files).

Any help would be appreciated.

+4
source share
2 answers

hint and plugins are the main parameters. hint allows you to interpret functions as bytecode; plugins use compiled object code.

Please note that since these eval functions must be checked for type before they are run, they are rarely pure values, since the evaluation may fail with a type error.

+3
source

Abstract answer: you just need to make (->) instance of Read (and maybe Show while you're on it)

How, in fact, you should do this, I do not know. This is a small task to interpret the code.

If you are dealing with simple functions, I would suggest creating a type of algebraic data to represent it.

 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 
-1
source

Source: https://habr.com/ru/post/1340498/


All Articles