Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run OCaml + Core script?

Tags:

ocaml

I am trying the Real World OCaml book. It talks about installing OPAM, then OCaml and Jane Street Core. I got utop loaded properly per the book instructions so that it automatically loads Core.

Without Core, I can run a generic OCaml script simply by ocaml script.ml without compiling. But this doesn't work if the script uses Core. What's the right command if I want to run a Core based OCaml script without compiling?

like image 888
Opa Avatar asked Nov 22 '13 03:11

Opa


People also ask

What does OCaml compile to?

OCaml comes with two compilers: ocamlc is the bytecode compiler, and ocamlopt is the native code compiler. If you don't know which one to use, use ocamlopt since it provides executables that are faster than bytecode. The compiler produces an executable named program or program.exe .


1 Answers

Running a script that depends on additional libraries requires you to tell the compiler where to find the libraries. Your best option is to use ocamlscript, which you can also install with OPAM. Just do opam install ocamlscript. Then read about ocamlscript here. Here's a working example:

$ cat a.ml
#! /usr/bin/env ocamlscript
Ocaml.ocamlflags := ["-thread"];
Ocaml.packs := [ "core" ]
--
open Core.Std

let () = print_endline "hello"

Make sure a.ml has the executable bit set. Then run it:

$ ./a.ml
hello

As a bonus, ocamlscript also compiles to native code, so you get high performance scripts.

like image 112
Ashish Agarwal Avatar answered Sep 20 '22 22:09

Ashish Agarwal