OCaml By Examples

Language Basics

Project Management

  • dune
  • dune-release
  • opam pin

Advanced Ocaml

  • functors
  • monads

Libraries

Hello World

hello.ml

There's no main function in OCaml, rather statements that can have side effects (here printing to stdout).
(* this is a comment *)
print_endline "hello world"
A more idiomatic way to write this is to enforce that the code returns nothing, or in OCaml term that it returns the "unit" symbol `()`.
let () = print_endline "hello world"

console

You can compile your code with the OCaml compiler `ocamlc`, similar to C programs.
$ ocamlc -o your_program hello.ml
$ ./your_program
hello world
hello world

hello2.ml

We can use the `core` library we installed in the previous example by "opening" it. We can then use Core's [printf](https://ocaml.janestreet.com/ocaml-core/odoc/stdlib/Stdlib/Printf/index.html) function directly. Notice that arguments of a function are not surrounded by parenthesis or commas.
open Core

let () = 
  printf "%s\n" "hello world"

console2

To compile code using external libraries, you can use `ocamlfind` which will do the work of finding and linking these libraries at compilation time.
$ opam install ocamlfind
$ ocamlfind opt -package core -thread -linkpkg hello2.ml
$ ./a.out
hello world
next: Utop