Skip to content
AgileLogics

F# Cheat Sheet

Learn F# from the basics →

Values & Types

let name = "Ada"
Immutable value (type inferred as string)
let mutable count = 0
Mutable variable; update with count <- count + 1
let age: int = 36
Explicit type annotation
int "42" / float 3 / string 7
Conversion functions
3.0 / 2.0 vs 3 / 2
Float division (1.5) vs integer division (1)
$"Hi {name}, {x:F2}"
Interpolated string with a format
()
The unit value — "no meaningful result"

Functions

let add a b = a + b
Function with two parameters (curried)
let add5 = add 5
Partial application
fun x -> x * 2
Lambda (anonymous function)
let rec fact n = if n <= 1 then 1 else n * fact (n - 1)
Recursive function needs rec
xs |> List.map f |> List.sum
Pipeline: pass the value on the left to the function on the right
let g = f >> h
Function composition (f, then h)

Collections

[1; 2; 3] / 0 :: xs / xs @ ys
List literal / prepend / concatenate
[| 1; 2; 3 |] / arr[0]
Array literal / zero-based index
seq { 1 .. 10 } / [ for i in 1 .. 5 -> i * i ]
Lazy sequence / list comprehension
List.map / filter / fold / sumBy / sortBy / groupBy
Core collection functions (also in Array and Seq)
Map.ofList [("a", 1)] |> Map.add "b" 2
Immutable dictionary
Set.ofList [3; 1; 3]
Immutable sorted set

Records & Unions

type Person = { Name: string; Age: int }
Record type
{ p with Age = 37 }
Copy a record with changes
type Shape = Circle of float | Square of float
Discriminated union
type OrderId = OrderId of int
Single-case union wrapper for domain types
type Counter() = member val Count = 0 with get, set
Class with an auto-property

Pattern Matching

match x with | 0 -> "zero" | n when n < 0 -> "neg" | _ -> "pos"
Match with a guard and a wildcard
| Circle r -> Math.PI * r * r
Deconstruct a union case
| [] -> ... | head :: tail -> ...
List patterns
let (a, b) = pair
Destructure a tuple
function | Some x -> x | None -> 0
Shorthand for fun v -> match v with
let (|Even|Odd|) n = if n % 2 = 0 then Even else Odd
Active pattern

Options & Results

Some 42 / None
Option: a value that may be missing
Option.map f / Option.defaultValue 0
Transform / unwrap with a fallback
Ok value / Error "message"
Result: success or failure
Result.bind validate
Chain steps that can fail
try ... with ex -> ...
Catch exceptions
failwith "message" / invalidArg "x" "bad"
Raise exceptions

Async & Computation Expressions

task { let! r = client.GetStringAsync url in return r.Length }
.NET Task (use for interop and web)
async { do! Async.Sleep 100; return 1 }
F# Async (cold, cancellable)
Async.Parallel jobs |> Async.RunSynchronously
Run many asyncs concurrently
seq { yield 1; yield! [2; 3] }
Sequence expression
let! / do! / return / return! / use!
Keywords inside computation expressions

Tooling

dotnet new console -lang F# -o MyApp
Create a console project
dotnet run / dotnet build / dotnet test
Run, build, and test a project
dotnet fsi script.fsx
Run an F# script (no project needed)
#r "nuget: FSharp.Data"
Reference a NuGet package from a script
dotnet add package Expecto
Add a NuGet package to a project
dotnet fantomas .
Format code with Fantomas (installed as a tool)