Values in OCaml

Our first example will demonstrate various value types in OCaml, including strings, integers, floats, and booleans. Here’s the full source code:

(* Strings, which can be concatenated with ^ *)
let () = print_endline ("ocaml" ^ "lang")

(* Integers and floats *)
let () = Printf.printf "1+1 = %d\n" (1 + 1)
let () = Printf.printf "7.0/3.0 = %f\n" (7.0 /. 3.0)

(* Booleans, with boolean operators as you'd expect *)
let () = Printf.printf "%b\n" (true && false)
let () = Printf.printf "%b\n" (true || false)
let () = Printf.printf "%b\n" (not true)

To run the program, save the code in a file named values.ml and use the OCaml compiler:

$ ocamlc -o values values.ml
$ ./values
ocamllang
1+1 = 2
7.0/3.0 = 2.333333
false
true
false

Let’s break down the code:

  1. In OCaml, strings are concatenated using the ^ operator.
  2. For integer arithmetic, we use standard operators like +.
  3. For floating-point arithmetic, we use special operators like /. for division.
  4. Boolean operations use && for AND, || for OR, and not for negation.
  5. We use Printf.printf for formatted output, similar to C’s printf function.

Note that OCaml is a statically-typed language with type inference, so we don’t need to explicitly declare types in most cases. The compiler will infer the correct types based on how we use the values.