TExcelTAD
Home › OCaml › OCaml Exercises

OCaml Exercises

Time to practise! Each exercise has a starter playground that compiles and runs as-is, printing a placeholder result so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. If you get stuck, open the solution, but try for a few minutes first.

# Exercise Topics
1 Temperature table for loops, floats, Printf
2 Count vowels strings, fold
3 Run-length encoding lists, pattern matching, recursion
4 Safe statistics options, fold_left
5 Shapes variants, records
6 Word frequencies Map, sorting
7 A stack module signatures, abstract types, result
8 Binary tree depth recursive variants

1. Temperature table

Print Celsius values 0, 25, 50, 75 and 100 with their Fahrenheit equivalents (F = C × 9/5 + 32), formatted as 0 C = 32.0 F (Celsius right-aligned in 3 characters, Fahrenheit in 5 with one decimal).

Expected first line 0 C = 32.0 F, last line 100 C = 212.0 F.

ocaml · try it yourself
let () =
  (* TODO: loop from 0 to 100 in steps of 25 *)
  let c = 0 in
  let f = 0.0 (* TODO: use the formula *) in
  Printf.printf "%d C = %f F\n" c f
0 C = 0.000000 F
Show solution
ocaml
let () =
  for i = 0 to 4 do
    let c = i * 25 in
    let f = (float_of_int c *. 9. /. 5.) +. 32. in
    Printf.printf "%3d C = %5.1f F\n" c f
  done

2. Count vowels

Write count_vowels : string -> int that counts a e i o u, ignoring case.

Expected: count_vowels "Programming in OCaml" is 6, and count_vowels "rhythm" is 0.

ocaml · try it yourself
let count_vowels s =
  (* TODO: use String.fold_left and Char.lowercase_ascii *)
  ignore s;
  0

let () =
  Printf.printf "%d\n" (count_vowels "Programming in OCaml");
  Printf.printf "%d\n" (count_vowels "rhythm")
0
0
Show solution
ocaml
let count_vowels s =
  String.fold_left
    (fun n c -> match Char.lowercase_ascii c with 'a' | 'e' | 'i' | 'o' | 'u' -> n + 1 | _ -> n)
    0 s

3. Run-length encoding

Write encode : char list -> (int * char) list that groups consecutive equal characters: ['a';'a';'b';'c';'c';'c'] becomes [(2,'a'); (1,'b'); (3,'c')].

Expected output: 2a 1b 3c 1a.

ocaml · try it yourself
let encode (chars : char list) : (int * char) list =
  (* TODO: walk the list with a recursive helper and an accumulator *)
  ignore chars;
  []

let () =
  let input = List.of_seq (String.to_seq "aabccca") in
  encode input |> List.map (fun (n, c) -> Printf.sprintf "%d%c" n c) |> String.concat " " |> print_endline
Show solution
ocaml
let encode chars =
  let rec go acc = function
    | [] -> List.rev acc
    | c :: rest -> (
        match acc with
        | (n, c') :: acc_rest when c' = c -> go ((n + 1, c) :: acc_rest) rest
        | _ -> go ((1, c) :: acc) rest)
  in
  go [] chars

4. Safe statistics

Write mean : float list -> float option and max_elt : float list -> float option. Both return None for an empty list.

Expected:

text
mean: 4.50
max: 7.00
empty mean: none
ocaml · try it yourself
let mean (l : float list) : float option = ignore l; None (* TODO *)
let max_elt (l : float list) : float option = ignore l; None (* TODO *)

let show = function Some x -> Printf.sprintf "%.2f" x | None -> "none"

let () =
  let data = [ 3.0; 7.0; 2.5; 5.5 ] in
  Printf.printf "mean: %s\n" (show (mean data));
  Printf.printf "max: %s\n" (show (max_elt data));
  Printf.printf "empty mean: %s\n" (show (mean []))
mean: none
max: none
empty mean: none
Show solution
ocaml
let mean = function
  | [] -> None
  | l -> Some (List.fold_left ( +. ) 0. l /. float_of_int (List.length l))

let max_elt = function
  | [] -> None
  | x :: rest -> Some (List.fold_left Float.max x rest)

5. Shapes

Define a variant shape with Circle of float (radius), Rect of float * float and Triangle of float * float * float (three sides). Write area (use Heron's formula for triangles: with s = (a+b+c)/2, area = sqrt (s(s-a)(s-b)(s-c))) and name.

Expected:

text
circle 3.14
rect 6.00
triangle 6.00
ocaml · try it yourself
type shape = Circle of float (* TODO: add Rect and Triangle *)

let name = function Circle _ -> "circle"
let area = function Circle r -> Float.pi *. r *. r

let () = List.iter (fun s -> Printf.printf "%s %.2f\n" (name s) (area s)) [ Circle 1.0 ]
circle 3.14
Show solution
ocaml
type shape = Circle of float | Rect of float * float | Triangle of float * float * float

let name = function Circle _ -> "circle" | Rect _ -> "rect" | Triangle _ -> "triangle"

let area = function
  | Circle r -> Float.pi *. r *. r
  | Rect (w, h) -> w *. h
  | Triangle (a, b, c) ->
      let s = (a +. b +. c) /. 2. in
      sqrt (s *. (s -. a) *. (s -. b) *. (s -. c))

let () =
  List.iter (fun s -> Printf.printf "%s %.2f\n" (name s) (area s))
    [ Circle 1.0; Rect (2.0, 3.0); Triangle (3.0, 4.0, 5.0) ]

6. Word frequencies

Count the words of a sentence (lower-case, split on spaces) with Map.Make (String), then print the top 3, most frequent first, ties in alphabetical order.

Expected:

text
the 3
a 2
cat 2
ocaml · try it yourself
module SMap = Map.Make (String)

let text = "the cat saw a dog and the dog saw a cat on the mat"

let () =
  let counts = SMap.empty (* TODO: fold over the words with SMap.update *) in
  let ranked = SMap.bindings counts (* TODO: sort by count descending, then word *) in
  List.iteri (fun i (w, n) -> if i < 3 then Printf.printf "%s %d\n" w n) ranked;
  ignore text
Show solution
ocaml
let () =
  let counts =
    String.split_on_char ' ' text
    |> List.fold_left
         (fun m w -> SMap.update w (function None -> Some 1 | Some n -> Some (n + 1)) m)
         SMap.empty
  in
  let ranked =
    SMap.bindings counts |> List.sort (fun (w1, n1) (w2, n2) -> compare (n2, w1) (n1, w2))
  in
  List.iteri (fun i (w, n) -> if i < 3 then Printf.printf "%s %d\n" w n) ranked

Note that "dog" and "saw" also appear twice: the alphabetical tie-break puts "a" and "cat" first.

7. A stack module

Implement the signature below with a list. pop returns Error "empty stack" when the stack is empty, otherwise Ok (top, rest).

Expected:

text
size 3
popped 30
popped 20
size 1
error: empty stack
ocaml · try it yourself
module type STACK = sig
  type 'a t
  val empty : 'a t
  val push : 'a -> 'a t -> 'a t
  val pop : 'a t -> ('a * 'a t, string) result
  val size : 'a t -> int
end

module Stack : STACK = struct
  type 'a t = 'a list
  let empty = []
  let push _x s = s                         (* TODO *)
  let pop _s = Error "empty stack"          (* TODO *)
  let size _s = 0                           (* TODO *)
end

let () =
  let s = Stack.(empty |> push 10 |> push 20 |> push 30) in
  Printf.printf "size %d\n" (Stack.size s);
  let rec pop_n n s =
    if n = 0 then s
    else
      match Stack.pop s with
      | Ok (x, rest) -> Printf.printf "popped %d\n" x; pop_n (n - 1) rest
      | Error e -> Printf.printf "error: %s\n" e; s
  in
  let s = pop_n 2 s in
  Printf.printf "size %d\n" (Stack.size s);
  match Stack.pop Stack.empty with Ok _ -> () | Error e -> Printf.printf "error: %s\n" e
size 0
error: empty stack
size 0
error: empty stack
Show solution
ocaml
module Stack : STACK = struct
  type 'a t = 'a list
  let empty = []
  let push x s = x :: s
  let pop = function [] -> Error "empty stack" | x :: rest -> Ok (x, rest)
  let size = List.length
end

8. Binary tree depth

Using type tree = Leaf | Node of tree * int * tree, write depth (the number of nodes on the longest root-to-leaf path), sum and leaves (how many nodes have two Leaf children).

Expected: depth 3, sum 28, leaves 3.

ocaml · try it yourself
type tree = Leaf | Node of tree * int * tree

let depth (_ : tree) = 0   (* TODO *)
let sum (_ : tree) = 0     (* TODO *)
let leaves (_ : tree) = 0  (* TODO *)

let () =
  let t = Node (Node (Node (Leaf, 1, Leaf), 4, Leaf), 7, Node (Node (Leaf, 6, Leaf), 2, Node (Leaf, 8, Leaf))) in
  Printf.printf "depth %d, sum %d, leaves %d\n" (depth t) (sum t) (leaves t)
depth 0, sum 0, leaves 0
Show solution
ocaml
let rec depth = function Leaf -> 0 | Node (l, _, r) -> 1 + max (depth l) (depth r)
let rec sum = function Leaf -> 0 | Node (l, v, r) -> sum l + v + sum r

let rec leaves = function
  | Leaf -> 0
  | Node (Leaf, _, Leaf) -> 1
  | Node (l, _, r) -> leaves l + leaves r

Test yourself

In exercise 3, why does the helper reverse the accumulator at the end?

  1. To sort the groups
  2. Because new groups are consed onto the front, so the list is built backwards
  3. Because List.rev removes duplicates
  4. It is not necessary

In exercise 7, why can't code outside Stack write Stack.push 1 [2; 3]?

  1. Lists are immutable
  2. 'a Stack.t is abstract, so a list is not a stack outside the module
  3. push needs labels
  4. It is allowed