“Eval” a string in OCaml

橙三吉。 提交于 2019-12-21 05:14:27

问题


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.


回答1:


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)

example:

eval "let () = print_endline \"hello\";;"

Notice the trailing ;; in the code sample.

To use ocamlbuild, you will need to use both compiler-libs and compiler-libs.toplevel.




回答2:


OCaml is a compiled (not interpreted) language. So there's no simple way to do this. Certainly there are no language features that support it (as there are in almost every interpreted language). About the best you could do would be to link your program against the OCaml toplevel (which is an OCaml interpreter).



来源:https://stackoverflow.com/questions/33291754/eval-a-string-in-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!