Control Flow: Conditionals & Expressions

e1; e2 evaluates e1 (should be unit), then returns e2.

7.1 Everything is an expression

Both branches must have the same type.

if without else must have type unit.

let abs x = if x < 0 then -x else x
let sign x = if x > 0 then "pos" else if x < 0 then "neg" else "zero"

7.2 Sequencing with ;

e1; e2 evaluates e1 (should be unit), then returns e2.

let () =
  print_string "a";
  print_string "b";
  print_newline ()

7.3 begin ... end and parentheses

begin ... end is identical to ( ... ).

if debug then begin
  print_endline "debug on";
  dump_state ()
end

7.4 Match as control flow

let classify n =
  match n with
  | 0 -> "zero"
  | 1 | 2 | 3 -> "small"
  | n when n < 0 -> "negative"
  | _ -> "large"