Failure is part of the job
A function that looks up a customer might not find one. A function that parses an amount might be given "abc". A transfer might be refused for one of four reasons. None of these is a bug; each is a normal outcome that the caller must handle. Yet many languages express them in ways the type system cannot see: returning null, returning -1, or throwing an exception that the signature does not mention. The caller can forget to check, and the compiler will not object.
F#'s answer is to make missing values and failures ordinary values with ordinary types. A function that might not find a customer returns a Customer option; a function that might refuse a transfer returns a Result whose error side lists every reason it could fail. The type says so, the caller must deal with it, and a small set of functions makes dealing with it pleasant. This lesson teaches those types, a style of pipeline built on them, and the place exceptions still have. Along the way you will see that these are not special language features at all: option and Result are ordinary unions, defined in FSharp.Core with the same syntax you used in the lesson on records and unions.
Option: maybe a value
Definition— Option
The type 'T option is a union with two cases: Some value, holding a value of type 'T, and None, meaning there is no value. It replaces null for "might be missing" in F# code. Its type appears in signatures, as in Map.tryFind: 'Key -> Map<'Key,'T> -> 'T option, so callers know to expect absence.
Here an organisation's staff directory is searched for each employee's manager's email address. Any step can come up empty: the employee might not exist, might have no manager, the manager might not be on file, or might have no email.
// option: a value that may be missing, as a union of two cases, Some and None.
type Employee = { Name: string; ManagerId: int option; Email: string option }
let staff =
Map [ 1, { Name = "Olufemi"; ManagerId = None; Email = Some "olufemi@example.org" }
2, { Name = "Priya"; ManagerId = Some 1; Email = None }
3, { Name = "Mateo"; ManagerId = Some 2; Email = Some "mateo@example.org" }
4, { Name = "Sun"; ManagerId = Some 9; Email = None } ]
let findEmployee id = Map.tryFind id staff
// Option.bind chains steps that may each fail; Option.map transforms a value if present.
let managersEmail id =
findEmployee id
|> Option.bind (fun e -> e.ManagerId)
|> Option.bind findEmployee
|> Option.bind (fun m -> m.Email)
for id in [ 3; 2; 1; 4; 7 ] do
let name = findEmployee id |> Option.map (fun e -> e.Name) |> Option.defaultValue "(unknown)"
let email = managersEmail id |> Option.defaultValue "no manager email"
printfn "%d %-9s -> %s" id name email
// Matching on an option directly.
let describe id =
match findEmployee id with
| Some { Name = n; Email = Some address } -> $"{n} <{address}>"
| Some { Name = n; Email = None } -> $"{n} (no email)"
| None -> "nobody"
printfn "%s | %s | %s" (describe 1) (describe 2) (describe 99)
// Turning .NET's Try-methods and nulls into options.
let tryParseInt (s: string) =
match System.Int32.TryParse s with
| true, n -> Some n
| false, _ -> None
let fromDotNet: string = null
printfn "%A %A %A" (tryParseInt "42") (tryParseInt "4x2") (Option.ofObj fromDotNet)It prints:
3 Mateo -> no manager email
2 Priya -> olufemi@example.org
1 Olufemi -> no manager email
4 Sun -> no manager email
7 (unknown) -> no manager email
Olufemi <olufemi@example.org> | Priya (no email) | nobody
Some 42 None NoneThe four key functions:
| Function | When the option is Some x | When it is None |
|---|---|---|
Option.map f | Some (f x) | None |
Option.bind f (where f returns an option) | f x | None |
Option.defaultValue d | x | d |
Option.orElse other | itself | other |
managersEmail is three Option.bind steps in a pipeline. If any step produces None, the following steps are skipped and the result is None: Mateo's manager Priya has no email, Olufemi has no manager, and Sun's manager (number 9) is not on file. You never wrote an if ... = null check, and you could not have forgotten one.
Pattern matching works on options like any union, and patterns nest: Some { Name = n; Email = Some address } matches "an employee was found and has an email". %A prints options as Some 42 and None.
Meeting .NET. Libraries written in C# use null and Try-methods. Option.ofObj turns a possibly-null reference into an option, and a Try-method's (bool, value) result is matched into Some or None, as tryParseInt does. Converting at the boundary means the rest of your code never sees a null. (F# 9 added optional nullness checking for exactly this boundary: with it switched on, a .NET type that may be null is written string | null, and the compiler makes you handle it.)
Result and railway-oriented programming
An option says that something is missing, but not why. When the reason matters, use Result: a union of Ok value and Error reason. The error side can be any type; idiomatic F# uses a union that lists every way the operation can fail.
// Result: Ok with a value, or Error with a reason. The errors are a union too.
type TransferError =
| NotANumber of string
| NotPositive of decimal
| ExceedsLimit of amount: decimal * limit: decimal
| InsufficientFunds of needed: decimal * available: decimal
let parseAmount (text: string) =
match System.Decimal.TryParse(text, System.Globalization.CultureInfo.InvariantCulture) with
| true, amount -> Ok amount
| false, _ -> Error(NotANumber text)
let checkPositive amount =
if amount > 0m then Ok amount else Error(NotPositive amount)
let checkLimit limit amount =
if amount <= limit then Ok amount else Error(ExceedsLimit(amount, limit))
let checkBalance balance amount =
if amount <= balance then Ok(balance - amount) else Error(InsufficientFunds(amount, balance))
// Railway-oriented programming: each step runs only if the previous one succeeded.
let transfer balance text =
parseAmount text
|> Result.bind checkPositive
|> Result.bind (checkLimit 1000m)
|> Result.bind (checkBalance balance)
let explain error =
match error with
| NotANumber t -> $"'{t}' is not an amount"
| NotPositive a -> $"{a} must be more than zero"
| ExceedsLimit (a, l) -> $"{a} is over the {l} daily limit"
| InsufficientFunds (n, av) -> $"needs {n} but only {av} is available"
for input in [ "250.00"; "abc"; "-5"; "1500"; "900" ] do
match transfer 600m input with
| Ok newBalance -> printfn "%-7s ok, new balance %M" input newBalance
| Error e -> printfn "%-7s refused: %s" input (explain e)
// Result.map transforms a success; Result.mapError transforms a failure.
let asText = transfer 600m "100" |> Result.map (sprintf "balance %M") |> Result.mapError explain
printfn "%A" asTextIt prints:
250.00 ok, new balance 350.00
abc refused: 'abc' is not an amount
-5 refused: -5 must be more than zero
1500 refused: 1500 is over the 1000 daily limit
900 refused: needs 900 but only 600 is available
Ok "balance 500"transfer is the core of a banking rule written as a pipeline of four checks. Each check takes a value and returns a Result; Result.bind connects them so that the first Error short-circuits the rest. The error type TransferError is a complete, checked list of what can go wrong: if a new rule is added, its new case makes the compiler point at explain, which must now handle it.
Analogy, not a formal construction
Scott Wlaschin's well-known picture for this style is a railway with two tracks. Each function is a junction: a successful result continues along the top (success) track to the next function; a failure switches to the bottom (failure) track, which runs straight past all the remaining functions to the end. Result.bind is the piece of track that connects one junction to the next. Hence the name railway-oriented programming.
Result.map transforms the value on the success track and Result.mapError the value on the failure track, so a pipeline can turn its success into display text and its errors into messages at the very end.
A list of results
A common question: you have parsed every line of a file, each giving a Result, and you want either all the values or the first error. That is another fold, run from the right with List.foldBack so the values stay in order:
let parseAll (texts: string list) =
let parse (t: string) =
match System.Int32.TryParse t with
| true, n -> Ok n
| false, _ -> Error $"'{t}' is not a number"
List.foldBack
(fun text acc ->
match parse text, acc with
| Ok n, Ok ns -> Ok(n :: ns)
| Error e, _ -> Error e
| Ok _, Error e -> Error e)
texts
(Ok [])parseAll [ "1"; "2"; "3" ] gives Ok [1; 2; 3], and parseAll [ "1"; "x"; "3" ] gives Error "'x' is not a number". Functional programmers call this operation sequence or traverse; libraries provide it ready-made, but it is worth writing once to see that there is no magic in it.
Option and Result are closely related to a mathematical idea, the monad, which also underlies C#'s LINQ and the computation expressions of a later lesson. You do not need the theory to use them: bind simply means "if this step succeeded, feed its value to the next one".
Validation, and exceptions
Fail-fast is right for a sequence of dependent steps: there is no point checking the balance if the amount is not a number. For a form with independent fields, users want to hear about every problem at once. Then you run all the checks and combine their results, collecting the errors:
// Fail-fast (bind) stops at the first error. Validation should report every error.
type SignUp = { Name: string; Email: string; Age: int }
let validateName (name: string) =
if System.String.IsNullOrWhiteSpace name then Error [ "name is required" ] else Ok(name.Trim())
let validateEmail (email: string) =
if email.Contains '@' then Ok email else Error [ $"'{email}' is not an email address" ]
let validateAge (text: string) =
match System.Int32.TryParse text with
| true, age when age >= 13 && age <= 120 -> Ok age
| true, age -> Error [ $"age {age} is out of range" ]
| false, _ -> Error [ $"age '{text}' is not a number" ]
// Combine three results: succeed only if all succeed, otherwise collect all the errors.
let combine3 make r1 r2 r3 =
match r1, r2, r3 with
| Ok a, Ok b, Ok c -> Ok(make a b c)
| _ ->
let errors r = match r with Error es -> es | Ok _ -> []
Error(errors r1 @ errors r2 @ errors r3)
let validate name email age =
combine3 (fun n e a -> { Name = n; Email = e; Age = a }) (validateName name) (validateEmail email) (validateAge age)
for name, email, age in [ "Yaw", "yaw@example.org", "29"; "", "nope", "abc"; "Ines", "ines@example.org", "7" ] do
match validate name email age with
| Ok user -> printfn "welcome %s (%d)" user.Name user.Age
| Error errors -> printfn "please fix: %s" (String.concat "; " errors)
// Exceptions still exist in F#, for truly exceptional situations and for .NET interop.
exception OutOfStock of item: string
let reserve item =
if item = "saffron" then raise (OutOfStock item) else $"reserved {item}"
for item in [ "rice"; "saffron" ] do
try
printfn "%s" (reserve item)
with
| OutOfStock name -> printfn "sorry, no %s left" name
let safeDivide a b =
try
Ok(a / b)
with :? System.DivideByZeroException as ex ->
Error ex.Message
printfn "%A %A" (safeDivide 10 2) (safeDivide 1 0)It prints:
welcome Yaw (29)
please fix: name is required; 'nope' is not an email address; age 'abc' is not a number
please fix: age 7 is out of range
reserved rice
sorry, no saffron left
Ok 5 Error "Attempted to divide by zero."Each validator returns a Result whose error is a list of messages. combine3 succeeds only when all three succeed, building the record from the three values; otherwise it concatenates all the error lists. Libraries such as FsToolkit.ErrorHandling provide general versions of this (and a validation computation expression), but the idea fits in a few lines.
Exceptions in F#
F# has exceptions too, the same .NET exceptions C# uses. raise throws one; failwith "message" throws a general Exception with that message; try ... with catches, using pattern matching on the exception (:? DivideByZeroException as ex tests its type); and try ... finally guarantees cleanup. The exception keyword defines a lightweight exception type that can carry data and be matched like a union case, as OutOfStock is. The use keyword is F#'s equivalent of C#'s using: a value bound with use is disposed at the end of its scope.
Two details differ from C#. First, try ... with is an expression, so both branches must produce a value of the same type, as in safeDivide, where both produce a Result. Second, to rethrow the current exception from inside a with handler, after logging it, say, call reraise (), which keeps the original stack trace; raise ex would start a new one. And because a with block is a pattern match, an exception that matches none of its rules simply continues outwards, exactly as an unmatched catch does in C#.
When should F# code use exceptions rather than Result? The common view among F# developers:
- Use
Result(or option) for expected outcomes that the caller should decide about: validation failures, business rules, "not found". - Use exceptions for the unexpected: bugs, broken invariants, and infrastructure failures that the immediate caller cannot do anything useful about (the database is down). Let them propagate to a top-level handler that logs them.
- At the boundary with .NET, catch the specific exceptions a library is documented to throw for expected situations and convert them to
Result, assafeDividedoes, so the rest of your code stays on the railway.
Do not go to the other extreme and wrap every possible exception in a Result. A Result whose error case is "any exception" tells the caller nothing that an exception would not, and makes every signature longer.
Working with options and results day to day
Keep the happy path readable. Long chains of Result.bind with lambdas get noisy. The result { } computation expression, covered in a later lesson, lets you write the same railway as straight-line code with let!. Many codebases use FsToolkit.ErrorHandling for it, or define their own in a dozen lines.
Make error types specific to the operation. TransferError lists the ways a transfer can fail. A single global AppError union with fifty cases forces every function to pretend it might fail in all fifty ways. When a pipeline combines operations with different error types, map them into the caller's error type with Result.mapError.
Don't use Option.get or .Value. They throw on None and defeat the purpose. If you are certain a value is present, the types can usually be changed to say so.
Prefer option over sentinel values. Not -1 for "not found", not the empty string for "no email", not DateTime.MinValue for "never". Email: string option says exactly what it means.
Use ValueOption in hot paths. option is a reference type, so Some x allocates a small object. voption, with cases ValueSome and ValueNone, is a struct and does not allocate; F# 10 even allows it for optional method parameters. Most code never needs it.
Where these types come from
Tony Hoare introduced the null reference in ALGOL W in 1965 and decades later called it his "billion-dollar mistake", for the crashes and security holes it has caused. The alternative, a type that explicitly may or may not hold a value, came from the ML family: ML and OCaml call it option, and Haskell calls it Maybe. F# inherited option from OCaml and added Result to its core library in F# 4.1 (2017), after years in which every project defined its own.
The idea has since spread to most modern languages. Rust has Option and Result and a ? operator that does what Result.bind does; Swift has optionals; Kotlin and TypeScript track nullability in their types; and C# 8 added nullable reference types. If you learn to think in options and results in F#, the same habits carry over almost unchanged.
Common misconceptions
Misconception
"None is just F#'s spelling of null." None is a case of a type the compiler tracks: you cannot use an int option as an int without saying what happens when it is None. A null hides inside an ordinary-looking type and fails when touched.
Misconception
"Functional code never throws." F# code throws when something genuinely exceptional happens, and .NET libraries throw all the time. The discipline is to keep expected failures in the types, and to convert library exceptions into results at the boundary where they are expected.
Misconception
"Result.bind collects all the errors." It stops at the first one. That is correct for dependent steps and wrong for independent validations, which need a combining function like combine3, or a validation library.
Exercises
1. Options, results and errors
CoreComputationalWhat does this script print?
let run start =
start
|> Option.map (fun x -> x * 3)
|> Option.bind (fun x -> if x > 10 then Some(x - 10) else None)
|> Option.defaultValue 0
printfn "%d %d %d" (run (Some 4)) (run (Some 3)) (run None)
2. Options, results and errors
CoreComputationalUsing the lesson's transfer and explain functions, what does this print?
match transfer 600m "-2000" with
| Ok b -> printfn "ok %M" b
| Error e -> printfn "%s" (explain e)
3. Options, results and errors
CoreComputationalUsing the lesson's validate function, how many error messages does validate "" "a@b" "200" return?
4. Options, results and errors
StretchComputationalWhat does this script print? (printf adds no new line.)
let test x =
try
try
if x = 0 then failwith "zero"
printf "A"
finally
printf "B"
with Failure msg ->
printf "C(%s)" msg
test 1
test 0
printfn ""
5. Options, results and errors
Warm-upHumanA function looks up a customer's middle name, which many customers do not have. What should it return in idiomatic F#?
6. Options, results and errors
CoreHumanWhich of these situations are best modelled with Result rather than exceptions? (Choose all that apply.)
Further reading and resources
- Options · MicrosoftThe option type and the Option module.
- Results · MicrosoftThe Result type and the Result module.
- Railway oriented programming · Scott WlaschinThe talk and articles that named and popularised this style of error handling.
- Exception handling · Microsofttry...with, try...finally, raise, failwith and exception definitions.