If Else in OCaml

Branching with if and else in OCaml is straightforward.

(* Here's a basic example. *)
if 7 mod 2 = 0 then
  Printf.printf "7 is even\n"
else
  Printf.printf "7 is odd\n";

(* You can have an if statement without an else. *)
if 8 mod 4 = 0 then
  Printf.printf "8 is divisible by 4\n";

(* Logical operators like && and || are often useful in conditions. *)
if 8 mod 2 = 0 || 7 mod 2 = 0 then
  Printf.printf "either 8 or 7 are even\n";

(* In OCaml, let bindings are used to declare variables.
   The scope of these bindings can be controlled using in. *)
let num = 9 in
if num < 0 then
  Printf.printf "%d is negative\n" num
else if num < 10 then
  Printf.printf "%d has 1 digit\n" num
else
  Printf.printf "%d has multiple digits\n" num

To run this OCaml program, you would typically save it in a file with a .ml extension and use the OCaml compiler:

$ ocamlc -o if_else if_else.ml
$ ./if_else
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in OCaml, you don’t need parentheses around conditions, but the then and else keywords are required. The if-then-else construct is an expression in OCaml, which means it always returns a value.

OCaml doesn’t have a ternary operator like some languages, but the if-then-else expression can be used in a similar way since it returns a value.

In OCaml, indentation is not significant for the language syntax, but it’s good practice to indent your code for readability. Also, OCaml uses semicolons to separate expressions in a sequence, not to end every statement like in some other languages.