OCaml, lesson 1
OCaml is a functional language with a strong, static type system. The compiler checks every value's type before your program runs, so many mistakes are caught early. Let's start with the simplest thing a program can do: write text to the screen.
let () = print_endline "Hello, World!"print_endline takes a string, prints it, and then moves to a new line. Text in double quotes
is a string. Notice there are no parentheses around the argument: in OCaml you call a
function by writing its name followed by its arguments, separated by spaces.
let () =?An OCaml file is a list of definitions that run from top to bottom. let () = ... says "run this
expression, and I expect it to produce nothing useful". That "nothing" has a name: the unit
value, written (). Printing functions return unit, so let () = is the usual way to mark the
main part of a program.
To do several things in a row, separate them with a semicolon ;:
The semicolon goes between steps, so the last step has none.
print_string prints its argument and stays on the same line. Use print_newline () (or a
"\n" inside the string) when you want to finish the line:
Printf.printf takes a format string with placeholders and fills them in. %s is a string,
%d an integer and %f a floating-point number. Unlike print_endline, it does not add a new
line by itself, so end the format with \n:
The compiler checks the format against the values. Passing a string where %d expects an
integer is a compile error, not a surprise at run time.
Comments start with (* and end with *). They can span several lines, and they can even be
nested, which is handy when you comment out code that already contains a comment.
When you press Run, the compiler first checks the types of the whole file. If something does not fit, you get an error with a line number and nothing runs. Read the message carefully: it usually says which type it expected and which one it found. If the file compiles, OCaml runs the top-level definitions in order, from the first line to the last.
2 exercises to try what you just read.
let () =
print_endline "First line";
print_endline "Second line"let () =
print_string "Loading";
print_string "...";
print_endline "done" (* prints: Loading...done *)let () =
Printf.printf "%s turned %d this year\n" "OCaml" 30;
Printf.printf "Pi is about %.2f\n" 3.14159 (* Pi is about 3.14 *)(* This whole line is a comment. *)
let () = print_endline "This runs" (* a comment after code *)Hello, World!
I am learning OCaml.3...2...1...Liftoff!
Comet launched with 4 crew.