我正在尝试“评估”表示 OCaml 中的 OCaml 表达式的字符串。我想做一些与 Python 类似的事情eval https://docs.python.org/3/library/functions.html#eval.
到目前为止我还没有找到太多。这Parsing http://caml.inria.fr/pub/docs/manual-ocaml/libref/Parsing.html模块看起来可能会有帮助,但我无法找到一种方法来评估字符串。
这是如何做到的,但我没有告诉你。 (另外Parsing模块是关于解析的,而不是执行代码)
#require "compiler-libs" (* Assuming you're using utop, if compiling then this is the package you need *)
let eval code =
let as_buf = Lexing.from_string code in
let parsed = !Toploop.parse_toplevel_phrase as_buf in
ignore (Toploop.execute_phrase true Format.std_formatter parsed)
example:
eval "let () = print_endline \"hello\";;"
注意尾随;;
在代码示例中。
To use ocamlbuild
,您将需要同时使用compiler-libs
and compiler-libs.toplevel
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)