"Eval"是OCaml中的一个字符串

lez*_*ed1 4 ocaml eval

我正在尝试"eval"表示OCaml中OCaml表达式的字符串.我正在寻找与Python的eval相当的东西.

到目前为止,我找不到多少.该解析模块看起来可能是有益的,但我没能找到一种方法,只是EVAL一个字符串.

Edg*_*ian 10

这是怎么做的,但我没有告诉你.(此外,解析模块是关于解析,而不是执行代码)

#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)
Run Code Online (Sandbox Code Playgroud)

例:

eval "let () = print_endline \"hello\";;"
Run Code Online (Sandbox Code Playgroud)

注意;;代码示例中的尾随.

要使用ocamlbuild,您需要同时使用compiler-libscompiler-libs.toplevel.