I wonder which is the one comfortable way to program in Ocaml (in MAC).
I am currently using the VSCode to detect the syntactic and type errors, but then I use online interpreters to compile (it creates the ml) and to run examples on it; I mean, to instantiate variables, test examples etc. For example, I use the online: https://try.ocamlpro.com/.
I know this is not the best way to do it: for instance, if a package is not integrated (let us say num
), I cannot do opam install num
and open it.
So I wonder which is a proper option to have both (1) the cool interface like VSCode and (2) compile + test stuff on the fly.
I think I am close with the next option: I write ocaml
in the terminal and then a mode is opened:
OCaml version 4.10.2
#
#
#
...
There, I can write: #open Num;; #open List;; #let...
but I do not know how to load files on it.
Someone also told me there was something called "utop", but I have looked and it seems advanced for me.
Any help is appreciated!
This mode of development is fully supported by dune that offers dune utop command that will automatically build your project, link it with top-level and start it with all your modules (and external dependencies) available.
Now if you're not yet using dune, you might wonder how to start using it. While the dune documentation is good and thorough, nobody wants to actually spend hours learning Dune, if the only thing that they want is to play with OCaml. So here is the quick tip, to create a ready to run OCaml code, use dune init
, e.g.,
dune init proj play
This will create a play
folder that will have the full OCaml project skeleton fully ready to use. So let's enter it,
cd play
Now we can easily build and run our project,
dune exec play
We also have the play
library in the lib
folder. It is empty, but you can create any files there, and they will be available in your bin/main.ml
as well as in dune utop
, e.g., let's create a simple module,
(* file lib/say.ml *)
let hello () = print_endline "Hi!"
and then we can use it in our executable,
(* file bin/main.ml *)
let () = Play.Say.hello ()
and we can play in the OCaml toplevel with our libraries, e.g,
$ dune utop
and then in the utop shell
utop # Play.Say.hello ();;
Hi!
- : unit = ()
So what about vscode? So far we played in the console, but vscode
together with ocaml-platform can do this without leaving the comfort of your editor. You can even select pieces of code and send the toplevel (the default key binding is Shift-Enter
) that enables interactive and iterative, bottom-up development.