Learn OCAML with Real Code Examples
Updated Nov 20, 2025
Code Sample Descriptions
1
OCaml Counter and Theme Toggle
let count = ref 0
let isDark = ref false
let updateUI () =
Printf.printf "Counter: %d\n" !count;
Printf.printf "Theme: %s\n" (if !isDark then "Dark" else "Light")
let increment () = count := !count + 1; updateUI ()
let decrement () = count := !count - 1; updateUI ()
let reset () = count := 0; updateUI ()
let toggleTheme () = isDark := not !isDark; updateUI ()
(* Simulate actions *)
updateUI (); increment (); increment (); toggleTheme (); decrement (); reset ();
Demonstrates a simple counter with theme toggling using OCaml references and functions.
2
OCaml Simple Addition
let add a b = a + b
let () = Printf.printf "%d\n" (add 10 20)
Adds two numbers and prints the result.
3
OCaml Factorial
let rec factorial n = if n <= 1 then 1 else n * factorial (n - 1)
let () = Printf.printf "%d\n" (factorial 5)
Calculates factorial recursively.
4
OCaml Fibonacci Sequence
let rec fib n = if n < 2 then n else fib (n - 1) + fib (n - 2)
let () = for i = 0 to 9 do Printf.printf "%d\n" (fib i) done
Generates first 10 Fibonacci numbers recursively.
5
OCaml Max of Two Numbers
let max a b = if a > b then a else b
let () = Printf.printf "%d\n" (max 10 20)
Finds the maximum of two numbers.
6
OCaml List Sum
let rec sum_list lst = match lst with [] -> 0 | x::xs -> x + sum_list xs
let () = Printf.printf "%d\n" (sum_list [1;2;3;4;5])
Sums elements of a list recursively.
7
OCaml Even Numbers Filter
let print_even lst = List.iter (fun x -> if x mod 2 = 0 then Printf.printf "%d\n" x) lst
let () = print_even [1;2;3;4;5]
Prints even numbers from a list.
8
OCaml Conditional Counter Increment
let count = ref 3
if !count < 5 then count := !count + 1
let () = Printf.printf "%d\n" !count
Increment counter only if less than 5.
9
OCaml Resettable Counter
let count = ref 0
count := !count + 1
count := !count + 1
let () = Printf.printf "%d\n" !count
count := 0
let () = Printf.printf "%d\n" !count
Counter that increments and can be reset.
10
OCaml Theme Toggle Only
let isDark = ref false
let () = Printf.printf "%s\n" (if !isDark then "Dark" else "Light")
isDark := not !isDark
let () = Printf.printf "%s\n" (if !isDark then "Dark" else "Light")
isDark := not !isDark
let () = Printf.printf "%s\n" (if !isDark then "Dark" else "Light")
Toggles theme multiple times.