Learn ML with Real Code Examples
Updated Nov 20, 2025
Code Sample Descriptions
1
ML Counter and Theme Toggle
val count = ref 0
val isDark = ref false
fun updateUI () = (
print ("Counter: " ^ Int.toString(!count) ^ "\n");
print ("Theme: " ^ (if !isDark then "Dark" else "Light") ^ "\n")
)
fun increment () = (
count := !count + 1;
updateUI ()
)
fun decrement () = (
count := !count - 1;
updateUI ()
)
fun reset () = (
count := 0;
updateUI ()
)
fun toggleTheme () = (
isDark := not !isDark;
updateUI ()
)
(* Simulate actions *)
updateUI ();
increment ();
increment ();
toggleTheme ();
decrement ();
reset ();
Demonstrates a simple counter with theme toggling using ML variables and functions.
2
ML Fibonacci Sequence
fun fib 0 = 0
| fib 1 = 1
| fib n = fib(n-1) + fib(n-2)
fun printFib n =
if n < 10 then (
print (Int.toString(fib n) ^ "\n");
printFib (n+1)
) else ()
printFib 0;
Generates the first 10 Fibonacci numbers recursively.
3
ML Factorial Calculator
fun fact 0 = 1
| fact n = n * fact(n-1)
val result = fact 5;
print(Int.toString(result) ^ "\n");
Calculates factorial using recursion.
4
ML Prime Checker
fun isPrime n =
let
fun check i = i*i > n orelse (n mod i <> 0 andalso check (i+1))
in
if n < 2 then false else check 2
end;
val n = 13;
print(if isPrime n then "Prime\n" else "Not Prime\n");
Checks if a number is prime.
5
ML Sum of List
val lst = [1,2,3,4,5];
fun sum [] = 0
| sum (x::xs) = x + sum xs;
val result = sum lst;
print(Int.toString(result) ^ "\n");
Calculates the sum of a list.
6
ML Reverse String
fun reverseString s =
let
fun rev [] acc = acc
| rev (x::xs) acc = rev xs (x::acc)
in
String.implode (rev (String.explode s) [])
end;
val r = reverseString "HELLO";
print(r ^ "\n");
Reverses a string.
7
ML Multiplication Table
fun table n i =
if i > 10 then ()
else (
print(Int.toString(n) ^ " x " ^ Int.toString(i) ^ " = " ^ Int.toString(n*i) ^ "\n");
table n (i+1)
);
table 5 1;
Prints multiplication table of a number.
8
ML Celsius to Fahrenheit
val c = 25.0;
val f = (c * 9.0 / 5.0) + 32.0;
print (Real.toString(f) ^ "\n");
Converts Celsius to Fahrenheit.
9
ML Simple Alarm Simulation
val temp = 80;
val thresh = 75;
print(if temp > thresh then "Alarm: Temperature Too High!\n" else "Temperature Normal\n");
Simulates an alarm when a threshold is exceeded.
10
ML Random Walk Simulation
val steps = 10;
val _ = ref 0;
val pos = ref 0;
for i = 1 to steps do (
if Random.rand() < 0.5 then pos := !pos + 1 else pos := !pos - 1;
print(Int.toString(!pos) ^ "\n");
);
Simulates a 1D random walk.