“评估" OCaml中的字符串 [英] "Eval" a string in OCaml
问题描述
我正在尝试评估"表示OCaml中OCaml表达式的字符串.我正在寻找与Python的 eval 等效的东西.
I'm trying to "eval" a string representing an OCaml expression in OCaml. I'm looking to do something equivalent to Python's eval.
到目前为止,我还找不到很多. 解析模块看起来可能会有所帮助,但是我无法找到评估字符串的方法.
So far I've not been able to find much. The Parsing module looks like it could be helpful, but I was not able to find a way to just eval a string.
推荐答案
此处是操作方法,但我没有告诉您. (此外,解析模块是关于解析,而不是执行代码)
Here is how to do it, but I didn't tell you. (Also the Parsing module is about Parsing, not executing code)
#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)
示例:
eval "let () = print_endline \"hello\";;"
请注意代码示例中的尾随;;
.
Notice the trailing ;;
in the code sample.
要使用ocamlbuild
,您将需要同时使用compiler-libs
和compiler-libs.toplevel
.
To use ocamlbuild
, you will need to use both compiler-libs
and compiler-libs.toplevel
.
这篇关于“评估" OCaml中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!