“Eval” a string in OCaml

前端 未结 2 501
粉色の甜心
粉色の甜心 2021-02-09 20:44

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

2条回答
  •  别跟我提以往
    2021-02-09 21:11

    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.

提交回复
热议问题