Learn FSHARP with Real Code Examples
Updated Nov 18, 2025
Code Sample Descriptions
1
F# Counter and Theme Toggle
let mutable count = 0
let mutable isDark = false
let updateUI() =
printfn "Counter: %d" count
printfn "Theme: %s" (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 F# variables and console output.
2
F# Simple Calculator
let add a b = a + b
let subtract a b = a - b
let multiply a b = a * b
let divide a b = a / b
printfn "Add 5 + 3: %d" (add 5 3)
printfn "Subtract 5 - 3: %d" (subtract 5 3)
printfn "Multiply 5 * 3: %d" (multiply 5 3)
printfn "Divide 6 / 2: %d" (divide 6 2)
Demonstrates basic arithmetic operations using functions.
3
F# Factorial
let rec factorial n =
if n <= 1 then 1
else n * factorial (n - 1)
printfn "Factorial of 5: %d" (factorial 5)
Recursive factorial function in F#.
4
F# Fibonacci Sequence
let rec fibonacci n =
if n = 0 then 0
elif n = 1 then 1
else fibonacci(n-1) + fibonacci(n-2)
[0..9] |> List.iter (fun n -> printfn "%d" (fibonacci n))
Recursive Fibonacci sequence generator.
5
F# List Comprehension
let numbers = [1..10]
let squares = [for n in numbers do if n % 2 = 0 then yield n * n]
printfn "%A" squares
Using list comprehension to square even numbers.
6
F# Map Filtering
let scores = dict ["Alice",10; "Bob",5; "Charlie",12]
let highScores = scores |> Seq.filter (fun kv -> kv.Value >= 10) |> dict
printfn "%A" highScores
Filtering a map based on values.
7
F# Anonymous Functions
let add = fun x y -> x + y
printfn "%d" (add 3 7)
Using anonymous functions and piping.
8
F# Reduce Example
let numbers = [1;2;3;4;5]
let sum = List.fold (fun acc x -> acc + x) 0 numbers
printfn "%d" sum
Summing a list of numbers using List.fold.
9
F# Zip and Map
let xs = [1;2;3]
let ys = [4;5;6]
let sums = List.map2 (+) xs ys
printfn "%A" sums
Combining two lists using zip and map.
10
F# Pattern Matching on Tuples
let addPair (x,y) = x + y
printfn "%d" (addPair (3,7))
Using pattern matching to destructure tuples.