Ocaml-代码的运行时编译为字符串 [英] Ocaml - Runtime compilation of code as a string

查看:56
本文介绍了Ocaml-代码的运行时编译为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析并编译我在运行时编写的函数,例如,我在运行时生成了以下字符串:

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*)

在OCaml中有没有办法做到这一点?我遇到了Dynlink,但我正在寻找一种更简单的方法.

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

推荐答案

没有比编译代码和 Dynlinking 结果库更简单的解决方案了.

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

或者等效地,可以使用REPL,将字符串写入文件系统,然后使用 #use 加载.

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

根据您的确切用例,可以选择MetaOCaml.

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

另一个重要的一点是,类型不能依赖于非依赖类型语言中的值.因此,需要限制 eval 的类型.例如,在Dynlinking路径中,动态链接函数的类型将由用于注册它们的钩子的类型决定.

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.

这篇关于Ocaml-代码的运行时编译为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆