7

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
  • 1
    Could you give details on your precise use case ?
    – Drup
    Oct 22, 2015 at 23:23

2 Answers 2

13

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.

3
  • This answer absolutely works in UTop, but I'm having trouble getting it to work with ocamlbuild. I'm requiring the same "compiler-libs" package (-pkg compiler-libs), but a get the error Reference to undefined global 'Toploop'
    – lezed1
    Oct 28, 2015 at 7:10
  • Actually, I figured it out and have edited your answer to reflect the correct package!
    – lezed1
    Oct 28, 2015 at 7:12
  • @lezed1 Okay but I really recommend you not use this, its completely side stepping the type system.
    – user1971598
    Oct 28, 2015 at 11:45
1

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).

3
  • I was thinking about using the functionality of top-level or utop. How can I link against it to provide eval like functionality? I think this is a useful file, but I can't figure out how to use it. github.com/ocaml/ocaml/blob/trunk/toplevel/toploop.ml
    – lezed1
    Oct 22, 2015 at 22:58
  • Also, this seems to be the actual Parser used by top-level: github.com/ocaml/ocaml/blob/…
    – lezed1
    Oct 22, 2015 at 23:02
  • @lezed1You can do it....ie compile it on the file and then exec the code, but this is the wrong way to code in OCaml. (Compiler-libs is where to look)
    – user1971598
    Oct 23, 2015 at 0:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.