OCaml By Examples

hello world


(* this is a comment *)
There are no `main()` function in OCaml, rather statements that can have side effects (here printing to stdout).
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"


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


We can also use [methods of the Core library]((https://ocaml.janestreet.com/ocaml-core/odoc/stdlib/Stdlib/Printf/index.html) we installed in the previous example. Notice that arguments of a function are not surrounded by parenthesis or commas.
let () =
  Core.printf "%s\n" "hello world"
You can also access a library's methods directly by opening the library. In general this is bad practice, unless the library is made to be opened (like Core).
open Core
let () = 
  printf "%s\n" "hello world"


To compile code using external libraries, you can use `ocamlfind` which will do the work of finding and linking these libraries at compilation time.<br> This is a bit cumbersome though; you will later learn about an easier way to build projects using [dune](build-dune.html).
$ opam install ocamlfind
$ ocamlfind opt -package core -thread -linkpkg hello2.ml
$ ./a.out
hello world
hello world
next: utop