F# · Lesson 6
Option and Result
Model "might be missing" with Option and "might fail" with Result, then chain steps into railway-style pipelines instead of null checks and exceptions.
In short
option:SomeorNone, never nullOption.map,Option.bind,Option.defaultValuechain with|>Result:OkorErrorwith a reasonbindfor steps that can fail,mapfor steps that cannot- Exceptions for outages,
Errorfor expected failures
Why F# code has (almost) no null
In TypeScript you write string | undefined and, with strictNullChecks, the compiler nags you to check it.
F# goes one step further: values of F# types (records, unions, lists, tuples) are never supposed to be null.
When a value might be missing you say so in the type with Option.
function findUser(id: number): User | undefined {
return users.find(u => u.id === id);
}
let findUser (id: int) : User option =
users |> List.tryFind (fun u -> u.Id = id)
User option(also writtenOption<User>) has exactly two shapes:Some userorNone.List.tryFindis the safe twin ofList.find. In F#, functions starting withtryreturn an option instead of throwing.
Option is just a discriminated union from the standard library:
type Option<'T> =
| None
| Some of 'T
So you consume it with match, exactly like your own unions:
const user = findUser(42);
const name = user !== undefined ? user.name : "guest";
let name =
match findUser 42 with
| Some user -> user.Name // `user` is the unwrapped User
| None -> "guest"
.NET libraries written in C# can still hand you null (for example a missing environment variable).
Convert at the boundary: Option.ofObj (System.Environment.GetEnvironmentVariable "PORT") gives None for null.
After that, the rest of your code never has to think about null again.
The Option module: stop matching everything by hand
Writing match for every option gets noisy. The Option module has small helpers. Each takes the option as the last argument so they chain with |>.
| F# | Meaning | Rough TS equivalent |
|---|---|---|
Option.map f opt | transform the value if there is one | x === undefined ? undefined : f(x) |
Option.bind f opt | f itself returns an option; don't nest | x === undefined ? undefined : f(x) where f may return undefined |
Option.defaultValue d opt | unwrap, with a fallback | x ?? d |
Option.orElse other opt | if None, try another option | x ?? other (where other may be undefined too) |
Option.filter pred opt | keep the value only if pred holds | x !== undefined && pred(x) ? x : undefined |
A realistic example: read a port from config, fall back to 8080.
function getPort(settings: [string, string][]): number {
const entry = settings.find(([key]) => key === "PORT");
const n = entry ? Number.parseInt(entry[1], 10) : NaN;
return Number.isNaN(n) ? 8080 : n;
}
let tryParseInt (s: string) : int option =
match System.Int32.TryParse s with
| true, n -> Some n
| false, _ -> None
let getPort (settings: (string * string) list) : int =
settings
|> List.tryFind (fun (key, _) -> key = "PORT")
|> Option.map snd
|> Option.bind tryParseInt
|> Option.defaultValue 8080
Line by line:
System.Int32.TryParse sis a .NET method with anoutparameter. F# turns it into a tuple(succeeded, value), and| true, n ->picks the number out.List.tryFind ...gives(string * string) option: the whole pair, if found.Option.map sndkeeps only the value part (sndreturns the second item of a pair), givingstring option.Option.bind tryParseInt:tryParseIntalready returns an option.Option.mapwould giveint option option;bindflattens it toint option.Option.defaultValue 8080leaves the option world with a plainint.
Result: failure with a reason
None says "nothing here" but not why. For validation and business rules you want the reason, so F# has Result:
type Result<'T, 'TError> =
| Ok of 'T
| Error of 'TError
In TypeScript you would hand-roll the same discriminated union:
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
function parseAge(input: string): Result<number, string> {
const n = Number.parseInt(input, 10);
if (Number.isNaN(n)) return { ok: false, error: `not a number: ${input}` };
if (n < 0) return { ok: false, error: "age cannot be negative" };
return { ok: true, value: n };
}
let parseAge (input: string) : Result<int, string> =
match System.Int32.TryParse input with
| false, _ -> Error $"not a number: {input}"
| true, n when n < 0 -> Error "age cannot be negative"
| true, n -> Ok n
Ok nandError "..."are the two cases; both sides of thematchmust produce the sameResult<int, string>.when n < 0is a guard: the case only matches if the condition holds.
Exceptions vs Result. In F# codebases, exceptions are for things that really are exceptional (a bug, the database is down).
Expected failures (bad input, a business rule saying no) are returned as Error values, so the type forces the caller to deal with them.
Errors as a discriminated union
Strings are fine for a quick script. At work, model errors as a union so callers can match on them:
type SignupError =
| { kind: "nameRequired" }
| { kind: "invalidEmail"; email: string }
| { kind: "tooYoung"; age: number };
type SignupError =
| NameRequired
| InvalidEmail of email: string
| TooYoung of age: int
let describe (error: SignupError) : string =
match error with
| NameRequired -> "Please enter your name"
| InvalidEmail email -> $"'{email}' is not a valid email"
| TooYoung age -> $"You must be 18 or older (you are {age})"
If you later add a case, the compiler warns about every match that forgot it. That is a huge win over string errors.
Railway-oriented programming
Picture two parallel tracks: the Ok track and the Error track. Each step either keeps you on the Ok track or switches you to the Error track. Once you are on the Error track, the remaining steps are skipped and the first error comes out at the end.
Result.map f:fis a normal function ('a -> 'b). It runs only onOk.Result.bind f:fis a step that can fail ('a -> Result<'b, 'e>). It runs only onOk, and the result is not nested.Result.mapError f: transforms the error. Use it to convert another module's error type into yours.
function register(form: Form): Result<User, SignupError> {
const name = validateName(form.name);
if (!name.ok) return name;
const email = validateEmail(form.email);
if (!email.ok) return email;
return { ok: true, value: { name: name.value, email: email.value } };
}
let register (form: Form) : Result<User, SignupError> =
validateName form.Name
|> Result.bind (fun name ->
validateEmail form.Email
|> Result.map (fun email -> { Name = name; Email = email }))
- If
validateNamereturnsError,Result.bindskips the lambda and passes the error through. - The lambdas are nested so that
nameis still in scope when we build the user. (The Computation Expressions topic showsresult { let! ... }, which flattens this.)
When each step takes the previous step's output, the pipeline reads top to bottom:
let processOrder (raw: string) : Result<Receipt, OrderError> =
raw
|> parseOrder // string -> Result<Order, OrderError>
|> Result.bind validateOrder // Order -> Result<Order, OrderError>
|> Result.map applyDiscount // Order -> Order (cannot fail)
|> Result.bind saveOrder // Order -> Result<Receipt, OrderError>
Result.bind needs both sides to use the same error type. When a step speaks a different error language, translate it with mapError:
type PaymentError =
| CardDeclined
| InsufficientFunds
type OrderError =
| InvalidOrder of string
| PaymentFailed of PaymentError
let pay (order: Order) : Result<Receipt, OrderError> =
chargeCard order.Total // Result<Receipt, PaymentError>
|> Result.mapError PaymentFailed // Result<Receipt, OrderError>
Union cases are functions, so PaymentFailed can be passed directly where a PaymentError -> OrderError is expected.
Validation: first error vs all errors
bind stops at the first error ("fail fast"). That is right for a pipeline where step 2 needs step 1's output.
Forms usually want every problem at once. Then you run the checks independently and collect the errors:
let errorsOf (result: Result<'a, 'e>) : 'e list =
match result with
| Ok _ -> []
| Error e -> [ e ]
let validateAll (form: Form) : Result<Form, SignupError list> =
let errors = errorsOf (validateName form.Name) @ errorsOf (validateEmail form.Email)
if List.isEmpty errors then Ok form else Error errors
Common beginner mistakes
mapwhere you neededbind. If the function already returns an option or result,mapgives youint option option. Usebind.- Calling
.Valueon an option.opt.Valuethrows onNone, just likeuser!.namein TS. Match, or useOption.defaultValue. - Wrong argument order. It is
Option.defaultValue 0 opt, notOption.defaultValue opt 0. The option always comes last. - Mixing the two types.
Option.bindon aResult(orOkwhereSomeis expected) is a type error. Use the matching module. - Throwing for validation.
failwith "bad email"hides the failure from the type. ReturnError (InvalidEmail email). - Mismatched error types in
bind. Align them withResult.mapErrorfirst. - Checking for null on F# values.
if user = nulldoesn't compile for records. Convert .NET nulls once withOption.ofObj.
Cheat sheet
Some 3, None // Option<'T>
Ok 3, Error "bad" // Result<'T, 'E>
List.tryFind / List.tryHead / Map.tryFind // safe lookups return options
Option.map f / Option.bind f // transform / chain a step that may be missing
Option.defaultValue d // x ?? d
Option.orElse (Some d) // try another option
Option.filter pred // Some -> None when pred is false
Option.ofObj value // .NET null -> None
Result.map f / Result.bind f // transform / chain a step that may fail
Result.mapError f // convert the error type
Result.defaultValue d / Result.toOption // leave the Result world
match r with
| Ok v -> ...
| Error e -> ...
Practise this lesson
In the app: a short video, 6 exercises checked by real tests and a 11-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.
Open in the app