The Toplevel (REPL) and Your First Program
3.1 Using utop
;; ends a toplevel phrase (only needed in the REPL, almost never in files).
Directives start with #: #use "file.ml";;, #require "str";;, #show List;;, #typeof "x";;, #trace f;;, #quit;;.
$ utop
# 1 + 2;;
- : int = 3
# let greeting = "Hello";;
val greeting : string = "Hello"
# #quit;;3.2 Hello World
Compile & run:
let () = ... pattern-matches the result against unit (), which acts as the program's "main" and ensures the expression has type unit.
let () = print_endline "Hello, World!"ocaml hello.ml # interpret directly
ocamlc -o hello hello.ml # bytecode executable
ocamlopt -o hello hello.ml # native executable
./hello3.3 Hello World with Dune
dune init project hello
cd hello
dune build
dune exec hellohello/
├── bin/
│ ├── dune (executable (public_name hello) (name main) (libraries hello))
│ └── main.ml
├── lib/
│ └── dune (library (name hello))
├── test/
│ ├── dune
│ └── test_hello.ml
├── dune-project
└── hello.opam3.4 Comments
There are no single-line // comments.
(* This is a comment *)
(* Comments (* can be nested *) in OCaml *)
(** This is a documentation comment, read by odoc *)