Ocaml - Runtime compilation of code as a string

Viewed 73

I want to parse and compile a function that I have written at runtime, for example I have the following string I generated at runtime:

let str = "fun x y z -> [x; y; z;]"

I am looking for something that will allow me to do something similar to:

let myfun = eval str 
(* eval returns the value returned by the code in the string so myfun will 
   have the type: 'a -> 'a -> 'a -> 'a list*)

Is there a way to do that in OCaml? I came across Dynlink but I am looking for a simpler way to do it.

1 Answers

There is no easier solution than compiling the code and Dynlinking the resulting library.

Or equivalently, one can use the REPL, write the string to the file system and them load it with #use.

Depending on your precise use case, MetaOCaml might be an alternative.

Another important point is that types cannot depend on values in a non-dependently typed language. Thus the type of eval needs to be restricted. For instance, in the Dynlinking path, the type of dynamically linked functions will be determined by the type of the hooks used to register them.

Related