All lessons

Your First Program

6 min · OCaml

Write and run your very first OCaml program, right here on the page.

OCaml · Your First Program0/5 cleared

Enemy 1 of 5

let () = ... — running an action

OCaml is a functional language with a strict, static type system — every expression has a type, and that type is checked before your program ever runs, which catches an entire category of bugs (like accidentally treating a string as a number) at compile time instead of at runtime. Despite that strictness, OCaml very rarely makes you write types out by hand: its type inference engine is powerful enough to figure out almost all of them on its own, so the code often reads as if it were dynamically typed even though it's thoroughly checked underneath.

OCaml treats "do something" and "compute a value" as closely related ideas — nearly everything in OCaml is an expression that produces a value, including things that look like statements in other languages. That mindset shows up immediately in your first program.

`let () = expression` is OCaml's way of saying "evaluate this expression for its side effect, and I don't care about its result." The `()` is OCaml's `unit` value — the type that carries no information, roughly OCaml's equivalent of `void` in other languages — and binding an expression's result to `()` is a declaration that you only want the expression's *effect* (like printing something), not a value to use later.

`print_endline` takes a string, prints it to standard output, and appends a newline afterward, so subsequent output starts on a fresh line. Its close relative `print_string` does the same without the trailing newline.

You
Binary Treant

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Hello, World!