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)
Cookies & your privacy
We use essential cookies to keep this site working and secure.
With your permission, we'd also like to use Google Analytics cookies to understand site traffic.
We don't use advertising or social media tracking cookies, and we honor Global Privacy Control (GPC) browser signals.
Learn more in our Privacy Policy.
Your browser is sending a GPC signal, so analytics stays off even if you accept.