View Category

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
ocaml
if name = "Bob"
then print_string "Hello, Bob!"

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
ocaml
if age > 42
then print_string "You are old"
else print_string "You are young"

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

ocaml
if age > 84 then
print_endline "You are really ancient"
else if age > 30 then
print_endline "You are middle-aged"
else
print_endline "You are young"

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
ocaml
let numsuffix i =
match i with
| 11 | 12 | 13 -> "th"
| x when x mod 10 = 1 -> "st"
| x when x mod 10 = 2 -> "nd"
| x when x mod 10 = 3 -> "rd"
| _ -> "th"
;;
(* alternate implementation without using guards:
let numsuffix i =
match i with
| 11 | 12 | 13 -> "th"
| x -> match x mod 10 with
| 1 -> "st"
| 2 -> "nd"
| 3 -> "rd"
| _ -> "th"
*)

for i = 1 to 40 do
Printf.printf "%d%s " i (numsuffix i);
done;
print_newline ()

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
ocaml
let x = ref 1 ;;

while !x < 150 do
Printf.printf "%d," !x;
x := !x * 2;
done;

print_newline()

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
ocaml
let () =
Random.self_init ();
let rec loop () =
let n = (Random.int 6) + 1 in
print_int n;
if n <> 6 then (print_char ','; loop ())
else print_newline ()
in
loop ()

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
ocaml
let rec write_hello = function
0 -> ()
| n ->
print_string "Hello" ;
write_hello (n-1)
;;
write_hello 5;;
let write_hello n =
for i = 1 to n do
print_string "Hello";
done

let () = write_hello 5

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
ocaml
for i = 10 downto 1 do
Printf.printf "%d .. " i
done;
print_endline "Liftoff!"